代码改变世界

extern "C" 回顾

2013-07-31 16:01  清心朗静  阅读(269)  评论(0编辑  收藏  举报

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

试验如下:  

test.h:

extern "C" void CppPrintf(void);  

test.cpp:
#include <iostream>  

#include "test.h"  

using namespace std;  

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

main.cpp:

#include <stdlib.h>

 #include <stdio.h>

 #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的方式来链接它们。