欢迎来到程序员中文网!

首页 Linux Mysql C++ Python PHP JavaScript 资源下载 动态 开源推荐
我要投稿 投诉建议

C++ 与 C 混合编程:extern "C" 与 API 设计

时间:2026年08月12日 05:42:24 浏览:1

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
}
#endif

3. 设计可移植 API



  • 使用不透明指针(void*)隐藏 C++ 实现细节。

  • 提供工厂函数和销毁函数。


// C 头文件
struct MyObject;
MyObject* create_object();
void destroy_object(MyObject* obj);
int get_value(MyObject* obj);

4. 注意事项



  • 避免在 C 与 C++ 间传递异常。

  • 注意内存管理责任。

  • 使用 extern "C" 时不能使用函数重载。


混合编程在移植老代码或绑定库时非常有用。