全球最实用的IT互联网信息网站!

AI人工智能P2P分享&下载搜索网页发布信息网站地图

当前位置:诺佳网 > 电子/半导体 > 可编程逻辑 >

C语言里extern "C" 是什么意思?

时间:2020-09-07 11:09

人气:

作者:admin

标签:

导读:通常用于C++和C混合编程的时候,为了防止C++的编译器在编译C文件的时候出现错误。...

经常在C语言的头文件中看到下面的代码:

#ifdef__cplusplus extern"C"{ #endif //allofyourlegacyCcodehere #ifdef__cplusplus } #endif

这通常用于C++和C混合编程的时候,为了防止C++的编译器在编译C文件的时候出现错误;众所周知,C++可以进行函数名重载,但是C则没有这种功能,那这和extern "C"又有什么关系呢?
先看下面这个表格,如下所示;

未添加 extern "C"

test.h

#ifndefTEST_H #defineTEST_H voidfoo1(void); voidfoo2(void); voidfoo3(inti); #endif

test.c

voidfoo1(void){} voidfoo2(void){} voidfoo3(inti){} intmain(intargc,char**argv){ foo1(); foo2(); foo3(1); return0; }

编译这两个文件,生成test.o文件,通过objdump查看函数符号;

g++-ctest.ctest.h objdump-ttest.o

可以看到函数符号已经被编译器修改了;

添加extern "C"

test.h

#ifndefTEST_H #defineTEST_H #ifdef__cplusplus extern"C"{ #endif voidfoo1(void); voidfoo2(void); voidfoo3(inti); #ifdef__cplusplus } #endif #endif

test.c

#ifdef__cplusplus extern"C"{ #endif voidfoo1(void){} voidfoo2(void){} voidfoo3(inti){} #ifdef__cplusplus } #endif intmain(intargc,char**argv){ foo1(); foo2(); foo3(1); return0; }

编译这两个文件,生成test.o文件,通过objdump查看函数符号;

g++-ctest.ctest.h objdump-ttest.o

这时候函数符号是正确的;

extern "C"是告诉C++的编译器不要打我这些C函数的主意。

温馨提示:以上内容整理于网络,仅供参考,如果对您有帮助,留下您的阅读感言吧!
相关阅读
本类排行
相关标签
本类推荐

CPU | 内存 | 硬盘 | 显卡 | 显示器 | 主板 | 电源 | 键鼠 | 网站地图

Copyright © 2025-2035 诺佳网 版权所有 备案号:赣ICP备2025066733号
本站资料均来源互联网收集整理,作品版权归作者所有,如果侵犯了您的版权,请跟我们联系。

关注微信