天天看點

關于"#ifdef __cplusplus extern "C" "

Microsoft-Specific Predefined Macros __cplusplus Defined for C++ programs only.

意思是說,如果是C++程式,就使用extern "C"{ ,而這個東東,是指在下面的函數不使用的C++的名字修飾,而是用C的

The following code shows a header file which can be used by C and C++ client applications:

// MyCFuncs.h

#ifdef __cplusplus

extern "C" { //only need to export C interface if  used by C++ source code

#endif

__declspec( dllimport ) void MyCFunc();

__declspec( dllimport ) void AnotherCFunc();

#ifdef __cplusplus

}

#endif

      當我們想從C++中調用C的庫時,(注,驅動是用C寫的,連new、delete也不能用,郁悶)不能僅僅說明 一個外部函數,因為調用C函數的編譯代碼和調用C++函數的編譯代碼是不同的。如果你僅說明一個外部函數, C++編譯器假定它是C++的函數編譯成功了,但當你連接配接時會發現很可愛的錯誤。解決的方法就是指定它為C函數:

extern "c" 函數描述

指定一群函數的話:

extern "C"{

n個函數描述

}

如果想C和C++混用的話:

#ifdef _cplusplus

extern "C"{

#endif

n個函數描述

#ifdef _cplusplus

}

#endif

       extern "C"表示編譯生成的内部符号名使用C約定。

      C++支援函數重載,而C不支援,兩者的編譯規則也不一樣。函數被C++編譯後在符号庫中的名字與C語言的不同。例如,假設某個函數的原型為:

void foo( int x, int y );

       該函數被C編譯器編譯後在符号庫中的名字可能為_foo,而C++編譯器則會産生像_foo_int_int之類的名字(不同的編譯器可能生成的名字不同,但是都采用了相同的機制,生成的新名字稱為“mangled name”)。_foo_int_int這樣的名字包含了函數名、函數參數數量及類型資訊,C++就是靠這種機制來實作函數重載的。下面以例子說明,如何在C++中使用C的函數,或者在C中使用C++的函數。

//C++引用C函數的例子

//test.c

#include <stdio.h>

void mytest()

{

    printf("mytest in .c file ok/n");

}

//main.cpp

extern "C"

{

    void mytest();

}

int main()

{

    mytest();

    return 0;

}

      //在C中引用C++函數

      在C中引用C++語言中的函數和變量時,C++的函數或變量要聲明在extern "C"{}裡,但是在C語言中不能使用extern "C",否則編譯出錯。

//test.cpp

#include <stdio.h>

extern "C"

{

  void mytest()

  {

    printf("mytest in .cpp file ok/n");

  }

}

//main.c

void mytest();

int main()

{

  mytest();

  return 0;

}

//綜合使用

一般我們都将函數聲明放在頭檔案,當我們的函數有可能被C或C++使用時,我們無法确定是否要将函數聲明在extern "C"裡,是以,我們應該添加:

#ifdef __cplusplus

extern "C"

{

#endif

//函數聲明

#ifdef __cplusplus

}

#endif

如果我們注意到,很多頭檔案都有這樣的用法,比如string.h,等等。

//test.h

#ifdef __cplusplus

#include <iostream>

using namespace std;

extern "C"

{

#endif

void mytest();

#ifdef __cplusplus

}

#endif

    這樣,可以将mytest()的實作放在.c或者.cpp檔案中,可以在.c或者.cpp檔案中include "test.h"後使用頭檔案裡面的函數,而不會出現編譯錯誤。

//test.c

#include "test.h"

void mytest()

{

    #ifdef __cplusplus

    cout << "cout mytest extern ok " << endl;

    #else

    printf("printf mytest extern ok n");

    #endif

}

//main.cpp

#include "test.h"

int main()

{

    mytest();

    return 0;

}