C 與 C++ 混用專案裡,最常見的問題就是連結時找不到符號——因為 C++ 會做 name mangling,而 C 不會。解法是用 extern "C" 把 C++ 端的函數開放出 C 樣式的符號名。
int call_MyMath_sum(int, int);
int sum(int a, int b) {
return call_MyMath_sum(a, b);
}
#include <iostream>
using namespace std;
extern "C" {
int sum(int, int);
}
class MyMath {
public:
static int sum(int, int);
};
int MyMath::sum(int a, int b) {
return (a + b);
}
extern "C" int call_MyMath_sum(int a, int b) {
return (MyMath::sum(a, b));
}
int main(void) {
cout << sum(5, 6);
return 0;
}
main.o:
g++ -c -o main.o main.cpp
test.o:
gcc -c -o test.o test.c
main: main.o test.o
g++ -o main main.o test.o
all: clean main
clean:
rm -f test.o main.o
這裡有兩處 extern "C":一處宣告 C 檔提供的 sum,讓 C++ 端知道它是 C 連結;另一處包住 call_MyMath_sum 的定義,讓 C 端能找到它。
連結階段務必用 g++ 而非 gcc,因為 C++ 需要標準庫;編譯 .c 檔則用 gcc。順序上先各自編譯成 .o,最後由 g++ 統一連結,就不會出現 mangling 造成的 undefined reference。