這個(gè)例子主要實(shí)現(xiàn)C與C++的相互調(diào)用問題 c.h的實(shí)現(xiàn) #ifndef _c_h_ #define _c_h_ #ifdef __cplusplus extern "C" { #endif void C_fun(); #ifdef __cplusplus } #endif #endif c.c的實(shí)現(xiàn) #include "c.h" void C_fun() { }
在擦cpp.cpp中調(diào)用c.c中的C_test() cpp.cpp的實(shí)現(xiàn) #include "c.h" int main() { C_fun() } 其中__cplusplus是C++編譯器的保留宏定義.就是說C++編譯器認(rèn)為這個(gè)宏已經(jīng)定義了. 所以關(guān)鍵是extern "C" {} extern "C"是告訴C++編譯器件括號(hào)里的東東是按照C的obj文件格式編譯的,要連接的話按照C的命名規(guī)則去找. 那么C中是如何調(diào)用C++中的函數(shù)cpp_fun()呢? 因?yàn)楝F(xiàn)有C后有C++, 所以只能從C++的代碼中考慮了. 加入C++中的函數(shù)或變量有可能被C中的文件掉用,則應(yīng)該這樣寫,也是用extern "C"{} 不過是代碼中要加,頭文件也要加,因?yàn)榭赡苁荂++中也調(diào)用
cpp.h的實(shí)現(xiàn) #ifndef _c_h_ #define _c_h_ #ifdef __cplusplus extern "C" { #endif void CPP_fun(); #ifdef __cplusplus } #endif #endif
Cpp.cpp的實(shí)現(xiàn) extern "C" { //告訴C+++編譯器,擴(kuò)號(hào)里按照C的命名規(guī)則編譯 void CPP_fun() { ..... }
|