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


















 
 
 








 
 
 
 