#ifdef __cplusplus
extern "C" {
#endif
// C 風格函數宣告/定義
#ifdef __cplusplus
}
#endif
__cplusplus 是 C++ 編譯器預定義宏,確保該區塊僅在 C++ 編譯單元生效。
| 語言 | 符號生成規則 |
|---|---|
| C | 僅函數名(如 _f) |
| C++ | 編碼簽名(如 __Z1fv),支援重載 |
驗證實驗:
// test.cxx
extern "C" int f(void) { return 1; }
// 編譯對比
gcc -S test.cxx // 有 extern "C" → 符號 _f
gcc -S test.cxx // 無 extern "C" → 符號 __Z1fv
C 庫源碼 (f1.c):
extern "C" {
void f1() { return; }
}
編譯:gcc -c f1.c -o f1.o → 符號 _f1
C++ 調用端 (test.cxx):
extern void f1(); // 未加 extern "C" → 期望符號 __Z2f1v
int main() { f1(); return 0; }
鏈接錯誤:undefined reference to 'f1()' —— 符號不匹配。
// test.cxx 修正
extern "C" {
extern void f1(); // 告訴 C++ 編譯器用 C 符號規則
}
int main() { f1(); return 0; }
或在頭文件層面統一:
extern "C" {
#include "f.h"
}
extern "C" 指示 C++ 編譯器對區塊內函數採用 C 語言鏈接規約(不做 name mangling)。