https://blog.csdn.net/caspiansea/article/details/9676153 《如何用C语言封装 C++的类,在 C里面使用》
https://blog.csdn.net/SkyBlue05/article/details/82384904 《STM32 —C与C++混合开发》
在嵌入式领域,C和C++混合编程还是很常见的
一、C++调用C的函数
这个很简单,把c文件对应的h文件,全部用extern "C" {}包起来就是了
#ifdef __cplusplus
extern "C" {
#endif
//原本的头文件内容。
#ifdef __cplusplus
}
#endif
二、c调用c++的函数
1、c++中的非成员函数、非重载函数
这种情形是最简单的情形,只要把c++函数的定义和声明前面加extern "C"就能够被c调用。
// C++ 文件:
extern "C" int foo( int x );
extern "C" int foo( int x )
{
//...
}
这样,编译器会将foo函数编译成类似_foo符号,而不会编译成类似_foo_int符号
则C可以这样调用C++函数
// C 文件:
int foo( int x );
void cc( int x )
{
foo( x );
//...
}
2、c++中非成员函数、重载函数
原理是,把c++的重载函数,包装成异名函数
// C++ 文件
void foo( int x );
void foo( float x );
extern "C" void foo_i( int x )
{
foo( x );
}
extern "C" void foo_f( float x )
{
foo( x );
}
// C 文件这样调用c++的重载函数
void foo_i( int x );
void foo_f( float x );
void ccc( int x1, float x2 )
{
foo_i( x1 );
foo_f( x2 );
// ...
}
3、c++中的成员函数
这才是我们最需要的一种情形,原理无非又是包装,把成员函数包装成普通函数。
//a.cpp (想办法调用这个类的成员函数)
class Round
{
public:
float getArea();
float getArea(float R);
double getArea(double R);
}
//b.cpp (中间层,把类的成员函数封装成可以供C调用的形式)
Round round;
extern "C" float getArea(float R)
{
return round.getArea(R);
}
//b.h (中间层,把类的成员函数封装成可以供C调用的形式)
extern "C" float getArea(float R);
//main.c (本C文件可以调用b.h中的c++函数)
#include "b.h"
int main(void)
{
float a = getArea(1.5);//相当于调用了a.cpp中的成员函数
}