1、__cplusplus是C++编译器内置的宏
2、extern "C"是C++编译器识别,C编译器不识别
如只想知道怎样就能实现C/C++混合编程而不深究为什么的话, 可以一拉到底直接看总结.
首先, 在介绍C/C++混合编程之前, 先思考几个问题
C/C++混合编程是什么?
C/C++混合编程有什么用?
C/C++混合编程应该怎么实现?
下面, 简单讲讲我对C/C++混合编程的理解 :
C/C++混合编程是什么?
就像问题本身所说, C/C++混合编程也就是一个工程中, 在C函数中调用C++函数的方法, 在C++的函数中能够调用C函数的方法.
C/C++混合编程有什么用?
在我们日常开发中, 也许会遇到这么一些情况, 同事A, C非常牛逼, 但是对C++一窍不通; 同事B, C++信手拈来, 但是对C却满头雾水. 但是在工作中有这么一种需求, 同事A需要用到C++的方法, 同事B需要用到C的方法, 这怎么办?
没错, 最简单的就是, 同事A把C的代码写好, 然后同事B只管调用即可, 同理, 同事A只管调用同事B写好的C++代码, 各司其职, 提高工作效率.
C/C++混合编程应该怎么实现?
那么, 这混合编程究竟要怎么实现呢?
C++调用C:
太easy了,直接在C头文件中加上#ifdef __cplusplus
extern “C”
{
#endif
…(一些声明)
#ifdef __cplusplus
}
#endif即可
C调用C++
得封装一层C形式的接口(去除类,去除重载函数…)
直接上代码:
*testcplus.cc
#include "testcplus.h"
#include <iostream>
void TEST::test(int a){std::cout<< a << std::endl;}
void TEST::test(int a,int b){std::cout<< a << " " << b << std::endl;}
- testcplus.h
class TEST{
public:
TEST()=default;
//void test();
void test(int a);
void test(int a,int b);
//void test(int a,int b);
};
derived.h(由于derived.h是被C拿走引用的,故不应该包含任何C++的内容,包括
class
#include C++头文件 etc,此头文件只能封装函数使用
)
#ifdef __cplusplus
extern "C"
{
#endif
void calltest(int a);
void calltestdouble(int a,int b);
#ifdef __cplusplus
}
#endif
- derived.cc
#include "derived.h"
#include "testcplus.h"
void calltest(int a){
TEST *t = new TEST;
t->test(a);
}
void calltestdouble(int a,int b){
TEST *t = new TEST;
t->test(a,b);
}
main.c
#include "derived.h"
int main(){
calltest(11);
calltestdouble(11,22);
}
开始编译:
g++ testcplus.cc -fpic -shared -o libtest1.so(符号都为c++类型)
g++ derived.cc -fpic -shared -o libtest2.so -L. -ltest1(derived.h中的符号都转为C类型)
gcc main.c -L. -ltest2 -ltest1 -o main
./main 成功调用
ybg@ubuntu:~/test/c-c++ $ ./main
11
11 22
nm libtest1.so | c++filt | grep test
00000000000009dc t _GLOBAL__sub_I_testcplus.cc
00000000000008fa T TEST::test(int)
0000000000000936 T TEST::test(int, int)
nm libtest2.so | c++filt | grep test
00000000000006ea T calltest
0000000000000717 T calltestdouble
U TEST::test(int)
U TEST::test(int, int)
果不其然,libtest2.so的calltest和calltestdouble符号都为C风格的符号,可被C调用