你真的知道C語言里Extern "C" 的作用嗎?
大家好,我是小麥,今天是周末,但是也不能停下學(xué)習(xí)的腳步。
我經(jīng)常在C語言的頭文件中看到下面的代碼:
- #ifdef __cplusplus
- extern "C" {
- #endif
- // all of your legacy C code here
- #ifdef __cplusplus
- }
- #endif
這通常用于C++和C混合編程的時(shí)候,為了防止C++的編譯器在編譯C文件的時(shí)候出現(xiàn)錯(cuò)誤;
眾所周知,C++可以進(jìn)行函數(shù)名重載,但是C則沒有這種功能,那這和extern "C"又有什么關(guān)系呢?
先看下面這個(gè)表格,如下所示;
語言 | 描述 |
---|---|
C | 函數(shù)名可以作為唯一ID和代碼段的程序建立聯(lián)系 |
C++ | 因?yàn)橹剌d的關(guān)系,函數(shù)名符號(hào)會(huì)被破壞,從而會(huì)根據(jù)函數(shù)的參數(shù)不同而重新生成函數(shù)符號(hào) |
未添加 extern "C"
test.h
- #ifndef TEST_H
- #define TEST_H
- void foo1(void);
- void foo2(void);
- void foo3(int i);
- #endif
test.c
- void foo1(void){}
- void foo2(void) {}
- void foo3(int i){}
- int main(int argc,char** argv){
- foo1();
- foo2();
- foo3(1);
- return 0;
- }
編譯這兩個(gè)文件,生成test.o文件,通過objdump查看函數(shù)符號(hào);
- g++ -c test.c test.h
- objdump -t test.o
可以看到函數(shù)符號(hào)已經(jīng)被編譯器修改了;
添加extern "C"
test.h
- #ifndef TEST_H
- #define TEST_H
- #ifdef __cplusplus
- extern "C" {
- #endif
- void foo1(void);
- void foo2(void);
- void foo3(int i);
- #ifdef __cplusplus
- }
- #endif
- #endif
test.c
- #ifdef __cplusplus
- extern "C" {
- #endif
- void foo1(void){}
- void foo2(void) {}
- void foo3(int i){}
- #ifdef __cplusplus
- }
- #endif
- int main(int argc,char** argv){
- foo1();
- foo2();
- foo3(1);
- return 0;
- }
編譯這兩個(gè)文件,生成test.o文件,通過objdump查看函數(shù)符號(hào);
- g++ -c test.c test.h
- objdump -t test.o
這時(shí)候函數(shù)符號(hào)是正確的;
extern "C" 是告訴C++的編譯器不要打我這些C函數(shù)的主意。
好了,這次分享的比較簡(jiǎn)單,也挺實(shí)用,我們下期再見。
本文轉(zhuǎn)載自微信公眾號(hào)「小麥大叔」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系小麥大叔公眾號(hào)。