C++ 与 C 混合编程:extern "C" 与 API 设计
C++ 可以调用 C 代码,也可被 C 代码调用,通过 extern "C" 实现。
1. 在 C++ 中使用 C 库
extern "C" {
#include "my_c_lib.h"
}2. 在 C 中使用 C++ 函数
- C++ 端定义函数为
extern "C",使用__cplusplus宏做条件编译。 - 编译为动态库,供 C 程序链接。
#ifdef __cplusplus
extern "C" {
#endif
void cpp_function(int x);
#ifdef __cplusplus
}
#endif3. 设计可移植 API
- 使用不透明指针(void*)隐藏 C++ 实现细节。
- 提供工厂函数和销毁函数。
// C 头文件
struct MyObject;
MyObject* create_object();
void destroy_object(MyObject* obj);
int get_value(MyObject* obj);4. 注意事项
- 避免在 C 与 C++ 间传递异常。
- 注意内存管理责任。
- 使用
extern "C"时不能使用函数重载。
混合编程在移植老代码或绑定库时非常有用。
