新闻  |   论坛  |   博客  |   在线研讨会
#ifdef __cplusplus extern "C" { #endif”的定义
电子禅石 | 2020-02-18 10:44:38    阅读:1058   发布文章

平时我们在linux c平台开发的时候,引用了一些Cpp或者C的代码库,发现一些头文件有如下代码条件编译。

复制代码
#ifdef  __cplusplusextern "C" {#endif// 代码#ifdef  __cplusplus
}#endif
复制代码

这个是什么意思呢?一开始看到这个也很茫然。上网查找了一些资料。

主要作用:

为了在C++代码中调用用C写成的库文件,就需要用extern"C"来告诉编译器:这是一个用C写成的库文件,请用C的方式来链接它们。

原因:

 C++支持函数重载,而C是不支持函数重载的,两者语言的编译规则不一样。编译器对函数名的处理方法也不一样。

假设有这个一个函数原型:

void func(int a,int b)
{  //code  }

可能在C++编译之后会产生_func_int_int之类的名字,因为C++支持重载。而C编译之后,可能为_func。

关键字:extern "C" 表示编译生成的内部符号名使用C约定

复制代码
//C++引用C函数的例子//test.c#include <stdio.h>void mytest()
{
printf("mytest in .c file ok\n");
}//main.cppextern "C"{void mytest();
}int main()
{
mytest();return 0;
}
复制代码

复制代码
//在C中引用C++函数//在C中引用C++语言中的函数和变量时,C++的函数或变量要声明在extern "C"{}里,但是在C语言中不能使用extern "C",否则编译出错。//test.cpp#include <stdio.h>extern "C"{void mytest()
{
printf("mytest in .cpp file ok\n");
}
}//main.cvoid mytest();int main()
{
mytest();return 0;
}
复制代码

复制代码
//综合使用//一般我们都将函数声明放在头文件,当我们的函数有可能被C或C++使用时,我们无法确定是否要将函数声明在extern "C"里,所以,我们应该添加#ifdef __cplusplusextern "C"{#endif//函数声明#ifdef __cplusplus
}#endif
复制代码

如果我们注意到,很多头文件都有这样的用法,比如string.h,等等。

复制代码
//test.h#ifdef __cplusplus
#include <iostream>using namespace std;extern "C"{#endifvoid mytest();
#ifdef __cplusplus
}#endif
复制代码

 

这样,可以将mytest()的实现放在.c或者.cpp文件中,可以在.c或者.cpp文件中include "test.h"后使用头文件里面的函数,而不会出现编译错误。

复制代码
//test.c#include "test.h"void mytest()
{
#ifdef __cplusplus
cout << "cout mytest extern ok " << endl;#elseprintf("printf mytest extern ok n");#endif}//main.cpp#include "test.h"int main()
{
mytest();return 0;
}
复制代码

参考博文:

http://www.cnblogs.com/HappyXie/archive/2011/01/07/1929369.html


*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。

参与讨论
登录后参与讨论
属于自己的技术积累分享,成为嵌入式系统研发高手。
推荐文章
最近访客