extern "C"的惯用法
extern "C"
{
#i nclude "cExample.h"
}
/*
c语言头文件:cExample.h */
#ifndef C_EXAMPLE_H
#define C_EXAMPLE_H
externint add(int x,int y);
#endif
/*
c语言实现文件:cExample.c */
#i nclude "cExample.h"
int add( int x, int y )
{
return x + y;
}
//
c++实现文件,调用add:cppFile.cpp
extern "C"
{
#i nclude "cExample.h"
}
int main(int argc, char* argv[])
{
add(2,3);
return 0;
}
(注意这里如果用GCC编译的时候,请先使用gcc -c选项生成cExample.o,再使用g++ -o cppFile cppFile.cpp cExample.o才能生成预期的
c++调用
c函数的结果,否则,使用g++ -o cppFile cppFile.cpp cExample.c
编译器会报错;而当cppFile.cpp 文件中不使用下列语句
extern "C"
{
#i nclude "cExample.h"
}
而改用
#i nclude "cExample.h"
extern "C" int add( int x, int y );
时
)
如果C++调用一个C语言编写的.DLL时,当包括.DLL的头文件或声明
接口函数时,应加extern "C" { }。
(2)在C中引用C++语言中的
函数和
变量时,C++的头文件需添加extern "C",但是在C语言中不能直接引用声明了extern "C"的该头文件,应该仅将C文件中将C++中定义的extern "C"
函数声明为extern类型。
//C++头文件 cppExample.h
#ifndef CPP_EXAMPLE_H
#define CPP_EXAMPLE_H
extern "C" int add( int x, int y );
#endif
//C++实现文件 cppExample.cpp
#i nclude "cppExample.h"
int add( int x, int y )
{
return x + y;
}
/* C实现文件 cFile.c
/* 这样会编译出错:#i nclude "cppExample.h" */
extern int add( int x, int y );
int main( int argc, char* argv[] )
{
add( 2, 3 );
return 0;
}