你真的知道 C 語言裏 extern "C" 的作用嗎?
大家好,我是小麥,今天是週末,但是也不能停下學習的腳步。
我經常在 C 語言的頭文件中看到下面的代碼:
#ifdef __cplusplus
extern "C" {
#endif
// all of your legacy C code here
#ifdef __cplusplus
}
#endif
這通常用於C++
和C
混合編程的時候,爲了防止C++
的編譯器在編譯C
文件的時候出現錯誤;
衆所周知,C++
可以進行函數名重載,但是C
則沒有這種功能,那這和extern "C"
又有什麼關係呢?
先看下面這個表格,如下所示;
未添加 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
查看函數符號;
g++ -c test.c test.h
objdump -t test.o
可以看到函數符號已經被編譯器修改了;
添加 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
查看函數符號;
g++ -c test.c test.h
objdump -t test.o
這時候函數符號是正確的;
extern "C"
是告訴C++
的編譯器不要打我這些 C 函數的主意。
好了,這次分享的比較簡單,也挺實用,我們下期再見。
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/4HO8DqbMaI6kiaXCynf3iA