extern “C” 回顾

引入:在测试"extern "C" 与gcc, g++无关"时,使用到了extern "C"的概念,网上找篇文章回顾一下。

试验如下:

test.h:

extern "C" void CppPrintf(void);

test.cpp:

#include

include "test.h"

using namespace std;

void CppPrintf( void ) { cout << "Hellon"; }

main.cpp:

include

include

include "test.h"

int main( void ) { CppPrintf(); return 0; }

1. 先给 test.h 里的 void CppPrintf(void); 加上 extern "C",看用 gcc 和 g++ 命名有什么不同。

$ g++ -S test.cpp

$ less test.s

.globl CppPrintf <-- 注意此函数的命名

.type CppPrintf , @function

$ gcc -S test.cpp

$ less test.s

.globl CppPrintf <-- 注意此函数的命名

.type CppPrintf , @function

完全相同!

2. 去掉 test.h 里 void CppPrintf(void); 前面的 extern "C",看用 gcc 和 g++ 命名有什么不同。

$g++ -S test.cpp

$ less test.s

.globl _Z9CppPrintfv <-- 注意此函数的命名

.type _Z9CppPrintfv , @function

$ gcc -S test.cpp

$ less test.s

.globl _Z9CppPrintfv <-- 注意此函数的命名

.type _Z9CppPrintfv , @function

完全相同!

测试结论: 完全相同,可见 extern "C" 与采用 gcc 或 g++ 并无关系, 以上的试验还间接的印证了前面的说法:在编译阶段,g++ 是调用 gcc 的。

这里注意,使用extern "C" 必须加在c++文件中才起作用(包括通过include 头文件的方式间接包含)。

进入正题:

extern "C" 的含义使用参考如下链接:

http://blog.chinaunix.net/uid-21411227-id-1826909.html

关于extern "C"总结两条:

1、C++和C对产生的函数名字的处理是不一样的. 通过查看汇编文件(.s),可以看出区别。

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

原文链接: https://www.cnblogs.com/qingxinlangjing/p/3228023.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/98039

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月10日 上午4:33
下一篇 2023年2月10日 上午4:33

相关推荐