理解 extern "C"

extern "C"是为了让代码按照C的方式编译,链接。

$ cat 1.h

#ifdef __cplusplus
extern "C" {
#endif
void foo(void);
#ifdef __cplusplus
};
#endif
$ cat 1.cpp 
#include "1.h"
void foo(void)
{
}
$ g++ 1.cpp -c
$ objdump  -t 1.o | grep foo
00000000 g     F .text	00000006 foo

可见,1.cpp确实是按照C链接的。

如果去掉 extern "C",那么 foo默认将按照 C++ 链接方式:

$ objdump  -t 1.o | grep foo
00000000 g     F .text	00000006 _Z3foov
$ cat 2.cpp 

extern void foo(void);
int main(void)
{
	foo();
	return 0;
}
$ g++ 2.cpp  -c
$ objdump  -t 2.o | grep foo
00000000         *UND*	00000000 _Z3foov

2.cpp期望的是 C++链接方式的foo.因此,这个时候,会有link error:

$ g++ 2.cpp  1.o  
/tmp/cc1kZrnB.o: In function `main':
2.cpp:(.text+0x12): undefined reference to `foo()'
collect2: error: ld returned 1 exit status

解决方法是声明一个 extern "C"的 foo函数(可以通过 include 1.h实现):

$ cat 2.cpp 

#include "1.h"
int main(void)
{
	foo();
	return 0;
}

$ objdump  -t 2.o | grep foo
00000000         *UND*	00000000 foo

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章