c++和c文件中的函数的互调的方法都是使用extern "C".
1. c++文件中的函数调用c文件中的函数。
例子如下:假设test.cpp文件中需要调用a.c文件中的fun函数。
//a.h
#ifndef A_H
#define A_H
extern int fun(int a, int b);
#endif
//a.c
#include "a.h"
#include <stdio.h>
int fun(int a, int b)
{
return a+b;
}
//test.h
#ifndef TEST_H
#define TEST_H
extern "C"{
#include "a.h"
}
#endif
//test.cpp
#include <iostream>
#include "test.h"
using namespace std;
int main(int argc, char **argv){
int sum = fun(2,3);
cout<<sum<<endl;
return 0;
}
编译方式: gcc -c a.h a.c 会生产a.o文件。
g++ -o test test.h test.cpp a.o会生成test可执行文件。./test运行得到输出结果。
2.c文件中调用c++文件中的函数。
例如a.c文件调用test.cpp文件中的fun函数。
<span style="font-family: Arial, Helvetica, sans-serif;">//test.cpp</span>
extern "C" int fun(int a, int b){
return a+b;
}
//a.c
#include <stdio.h>
#include "test.h"
int main(){
int sum = fun(2,3);
printf("sum=%d\n",sum);
return 0;
}
编译方式:g++ -c test.cpp -o test.o
gcc -c a.c -o a.o
g++ -o a a.o test.o
运行: ./a
总结:
1. extern "C"的含义是一种约定,表明编译和链接的时候按照c的风格进行。