理解 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

 

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