C++程序不能直接调用已编译后的C函数的,这是因为名称问题,举个例,一个函数叫做void foo(int x, int y),该函数被C编译器编译后在库中的名字为_foo,而C++编译器则会产生像_foo_int_int之类的名字用来支持函数重载和类型安全连接,名称就不一样,因此不能直接调用的。那要调用的话怎么办呢? C++提供了一个C连接交换指定符号***extern“C”***来解决这个问题。
extern “C”
{
void foo(int x, int y);
…// 其它函数
}
extern “C”
{
#include “myheader.h”
…// 其它C头文件
}
这就告诉C++编译译器,函数foo 是个C连接,应该到库中找名字_foo而不是找_foo_int_int。
//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"后使用头文件里面的函数,而不会出现编译错误。