在C++中調用C函數要顯示用extern 「C」聲明要調用的C文件中的函數,有以下兩種方法:ios
一、直接在C++中使用語句extern 「C」 f(int x, int y);編程
注意:此時C++文件中不要包含C的頭文件,這樣會出現頭文件裏的聲明和當前文件裏面對同一函數的聲明不相同。(注意C的頭文件中是不會出現extern 「C」這樣的關鍵字的)函數
代碼以下:spa
//C頭文件 CDemo.h #include <stdio.h> #ifndef C_SRC_DEMO_H #define C_SRC_DEMO_H extern int f(int x,int y); //或者int f(int x,int y); #endif // C_SRC_DEMO_H
//C代碼 #include "CDemo.h" int f(int x,int y) {
printf("In C file\n"); printf("x + y = %d\n",x+y); return 0; }
//C++代碼 cppDemo.cpp
#include <iostream> //#include "CDemo.h" //注意千萬不要有這句,否則生成可執行文件時通不過 extern "C" int f(int x,int y); int main() {
f(2,3); return 0; }
或者在C代碼中也不包含頭文件CDemo.h,上述代碼也能夠經過。code
二、在C++文件使用extern 「C」包含C的頭文件,C代碼同上blog
//C++代碼 #include <iostream> extern "C" {
#include "CDemo.h" }
int main() { f(2,3); return 0; }
在C++中使用大量現成的C程序庫,一般會有下面形式的聲明:io
#ifdef __cplusplus extern "C" { #endif /**** some declaration or so *****/ #ifdef __cplusplus } #endif /* end of __cplusplus */
結論:若想在C++中使用大量現成的C程序庫,實現C++與C的混合編程,那你必須瞭解extern "C"是怎麼回事兒,明白extern "C"的使用方式。class