2009年7月29日 星期三

extern "C" and #ifdef __cplusplus

__cplusplus is a macro that a C implementation is *not* allowed to
define in standard conforming mode. It's conventionally defined by
C++ compilers.

Th extern "C" line tells the compiler (C++ compiler) that the external information sent to the linker should use C calling conventions and name mangling (e.g., preceded by a single underscore). Since name overloading isn't supported by C, you can't make several overloaded functions simultaneously callable by a C program.

當你要寫一個C++程式時,其所宣告function要能被C程式所使用,就須使用extern "C" 宣告該function ,以下是一個例子,其方式如下:

g++ -c cppprog.cpp
gcc -c cmain.c
g++ -o cmain cmain.o cppporg.o
./cmain
hello cppmethod


//cppprog.h

#ifndef __CPPPROG_H
#define __CPPPROG_H

#ifdef __cplusplus
#include
using namespace std;
#endif


#ifdef __cplusplus
extern "C" {
#endif


extern void cppmethod();

#ifdef __cplusplus
}
#endif


#endif

//cppprog.cpp

#include "cppprog.h"

void cppmethod(){

cout<<"hello cppmethod\n";
}

//cmain.c

#include "cppprog.h"

int main(){

cppmethod();

}

參考:
http://bytes.com/groups/cpp/61576-c-call-c-fuction-iostream
http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html
http://www.velocityreviews.com/forums/t318522-help-with-cplusplus.html

沒有留言: