經(jīng)常在C語(yǔ)言的頭文件中看到下面的代碼:
#ifdef__cplusplus extern"C"{ #endif //allofyourlegacyCcodehere #ifdef__cplusplus } #endif
這通常用于C++和C混合編程的時(shí)候,為了防止C++的編譯器在編譯C文件的時(shí)候出現(xiàn)錯(cuò)誤;眾所周知,C++可以進(jìn)行函數(shù)名重載,但是C則沒(méi)有這種功能,那這和extern "C"又有什么關(guān)系呢?
先看下面這個(gè)表格,如下所示;
未添加 extern "C"
test.h
#ifndefTEST_H #defineTEST_H voidfoo1(void); voidfoo2(void); voidfoo3(inti); #endif
test.c
voidfoo1(void){} voidfoo2(void){} voidfoo3(inti){} intmain(intargc,char**argv){ foo1(); foo2(); foo3(1); return0; }
編譯這兩個(gè)文件,生成test.o文件,通過(guò)objdump查看函數(shù)符號(hào);
g++-ctest.ctest.h objdump-ttest.o
可以看到函數(shù)符號(hào)已經(jīng)被編譯器修改了;

添加extern "C"
test.h
#ifndefTEST_H #defineTEST_H #ifdef__cplusplus extern"C"{ #endif voidfoo1(void); voidfoo2(void); voidfoo3(inti); #ifdef__cplusplus } #endif #endif
test.c
#ifdef__cplusplus extern"C"{ #endif voidfoo1(void){} voidfoo2(void){} voidfoo3(inti){} #ifdef__cplusplus } #endif intmain(intargc,char**argv){ foo1(); foo2(); foo3(1); return0; }
編譯這兩個(gè)文件,生成test.o文件,通過(guò)objdump查看函數(shù)符號(hào);
g++-ctest.ctest.h objdump-ttest.o
這時(shí)候函數(shù)符號(hào)是正確的;

extern "C"是告訴C++的編譯器不要打我這些C函數(shù)的主意。
-
C語(yǔ)言
+關(guān)注
關(guān)注
183文章
7636瀏覽量
144229
原文標(biāo)題:長(zhǎng)見識(shí):你真的知道C語(yǔ)言里extern "C" 的作用嗎?
文章出處:【微信號(hào):gh_c472c2199c88,微信公眾號(hào):嵌入式微處理器】歡迎添加關(guān)注!文章轉(zhuǎn)載請(qǐng)注明出處。
發(fā)布評(píng)論請(qǐng)先 登錄
第4章 C語(yǔ)言基礎(chǔ)以及流水燈的實(shí)現(xiàn)(4.3 4.4)
主流的 MCU 開發(fā)語(yǔ)言為什么是 C 而不是 C++?
深入理解C語(yǔ)言:C語(yǔ)言循環(huán)控制
如何在 樹莓派 上編寫和運(yùn)行 C 語(yǔ)言程序?
EE-128:C語(yǔ)言中的DSP:從C調(diào)用匯編類成員函數(shù)
使用C語(yǔ)言實(shí)現(xiàn)函數(shù)模板
C語(yǔ)言中的socket編程基礎(chǔ)
TMS320C28x匯編語(yǔ)言工具

C語(yǔ)言里extern "C" 是什么意思?
評(píng)論