在很多程序中,都会见到如下代码段:
#ifdef __cplusplus
extern "C" {
#endif
/*
* C代码段
*/
#ifdef __cplusplus
}
#endif
__cplusplus是C++中定义的宏,表示这是一段C++代码,编译器按照C++的方式进行编译。如果这时我们需要使用C语言的代码,那么就需要加上extern "C" { 代码段 }说明一下该部分为C代码段,编译器用C语言的模式编译,否则编译器会把C代码按照C++模式编译,会报错。
主要是因为C++支持函数重载,而C不支持,两者的编译规则也不一样。函数被C++编译后在符号库中的名字和C语言不同。例如,假设某个函数原型为:void foo(int x, int y);该函数被C编译器编译后在符号库中的名字可能为_foo,而C++编译器则会产生像_foo_int_int之类的名字(不同编译器生成的名字可能不同,但是都采用了相同的机制)。_foo_int_int这样的名字包含了函数名、参数数量以及参数类型信息,C++就是靠这种机制来实现函数重载的。
1、在C++代码中调用C函数(***常用)
test.h
#ifndef _TEST_H_
#define _TEST_H_
#ifdef __cplusplus
extern "C" {
#endif
int add(int x, int y);
#ifdef __cplusplus
}
#endif
#endif
test.c
#include "test.h"
int add(int x, int y)
{
return x + y;
}
main.cpp
#include <iostream>
#include "test.h"
using namespace std;
using std::cout;
using std::endl;
int main(int argc, char *argv[])
{
int a = 2;
int b = 8;
cout << "sum = " << add(a, b) << endl;
return 0;
}
结论:在C++代码中调用C函数时,则需在相应的C(.h)头文件中加上extern "C" {} 。
2、在C代码中调用C++函数
test.h
#ifndef _TEST_H_
#define _TEST_H_
#ifdef __cplusplus
extern "C" {
#endif
int add(int x, int y);
#ifdef __cplusplus
}
#endif
#endif
test.cpp
#ifdef __cplusplus
extern "C" {
#endif
#include "test.h"
int add(int x, int y)
{
return x + y;
}
#ifdef __cplusplus
}
#endif
main.c
#include <stdio.h>
#include "test.h"
int main(int argc, char *argv[])
{
int a = 2;
int b = 8;
printf("sum = %d\n", add(a, b));
}
结论:在C代码中调用C++函数时,则需在相应的C++(.h)头文件和源文件(.cpp)中都加上extern "C" {}。
参考链接: