extern "c" 的用法

extern "C"主要是用于c++中代码应用c的代码

可以有以下几种情况:

1 在C的头文件中使用

#ifdef __cpluscplus  
extern "C" {  
#endif  
  
//some code  
  
#ifdef __cplusplus  
}  
#endif  

这样,C++代码中可以直接包含此C头文件,然后引用函数

2 在C的代码头文件中没有使用extern “c”

extern "C" {  
#include "test_extern_c.h"  
}  

则需要在C++的代码中对C的头文件加上extern “c”,或直接在函数前面加入extern “c”

3 如果在C中引用c++代码

在C中引用C++语言中的函数和变量时,C++的头文件需添加extern "C",但是在C语言中不能直接引用声明了extern "C"的该头文件,应该仅将C文件中将C++中定义的extern "C"函数声明为extern类型。
编写的C引用C++函数例子工程中包含的三个文件的源代码如下:
//C++头文件 cppExample.h
#ifndef CPP_EXAMPLE_H
#define CPP_EXAMPLE_H
extern "C" int add( int x, int y );
#endif
//C++实现文件 cppExample.cpp
#include "cppExample.h"
int add( int x, int y )
{
 return x + y;
}
/* C实现文件 cFile.c
/* 这样会编译出错:#include "cExample.h" */
extern int add( int x, int y );
int main( int argc, char* argv[] )
{
 add( 2, 3 );
 return 0;
}

posted on 2015-07-27 16:49  菜鸟基地  阅读(401)  评论(0)    收藏  举报

导航