在C++代码中包含非系统的C头文件,在#include中使用extern "C" { /*...*/ } ,这就告诉C++编译器包含在这个文件中的函数是C函数。
// This is C++ code
extern "C" {
// Get declaration for f(int i, char c, float x)
#include "my-C-code.h"
}
int main()
{
f(7, 'x', 3.14); // Note: nothing unusual in the call
...
}
在C代码中改变,以适应C++的方法,就是在C头文件的开始加入以下代码:
#ifdef_cplusplus
extern "C"{
#endif
头文件的最后加入以下代码
#ifdef_cplusplus
}
#endif
然后在C++中就可以直接引用了
// This is C++ code
// Get declaration for f(int i, char c, float x)
#include "my-C-code.h" // Note: nothing unusual in #include line
int main()
{
f(7, 'x', 3.14); // Note: nothing unusual in the call
...
}
如果不想在头文件中包含,也可使用extern “c”,同样也可以在C++中直接调用,例如:
extern "C" {
void f(int i, char c, float x);
int g(char* s, const char* s2);
double sqrtOfSumOfSquares(double a, double b);
}
int main()
{
f(7, 'x', 3.14); // Note: nothing unusual in the call
...
}
如何在C++函数中调用C函数,也是用extern "C".(告诉C++编译器函数链接是函数是C调用方式和 名字转换)如:
// This is C++ code
// Declare f(int,char,float) using extern "C":
extern "C" void f(int i, char c, float x);
// Define f(int,char,float) in some C++ module:
void f(int i, char c, float x)
{
}
如果没用extern "C",则会出现编译错误。
如何在C++的类对象中使用C函数,下面是实例代码:
Fred.h:
/* This header can be read by both C and C++ compilers */
#ifndef FRED_H
#define FRED_H
#ifdef __cplusplus
class Fred {
public:
Fred();
void wilma(int);
private:
int a_;
};
#else
typedef
struct Fred
Fred;
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if defined(__STDC__) || defined(__cplusplus)
extern void c_function(Fred*); /* ANSI C prototypes */
extern Fred* cplusplus_callback_function(Fred*);
#else
extern void c_function(); /* K&R style */
extern Fred* cplusplus_callback_function();
#endif
#ifdef __cplusplus
}
#endif
#endif /*FRED_H*/
Fred.cpp:
// This is C++ code
#include "Fred.h"
Fred::Fred() : a_(0) { }
void Fred::wilma(int a) { }
Fred* cplusplus_callback_function(Fred* fred)
{
fred->wilma(123);
return fred;
}
main.cpp:
// This is C++ code
#include "Fred.h"
int main()
{
Fred fred;
c_function(&fred);
} c-function.c:
/* This is C code */
#include "Fred.h"
void c_function(Fred* fred)
{
cplusplus_callback_function(fred);
}
这里要注意的是C++和C中指针的使用方式,另外在void*上两者使用方式也不同。
要安全的使用C函数在C++类中,那么这个类必须是没有虚函数(包括继承的虚函数),它的数据成员必须是同一个访问权限(private/protected/public),子对象中不能有虚函数。