《C++程序设计原理与实践》第2版
图书
1. C++中调用C函数

- C语言函数命名方式跟C++不同
- 当需要在C++中调用C函数时,需要使用extern "C"{}包裹C函数声明,否则C++编译器会报错
- 本质上,extern "C"的意思就是告诉编译器使用C连接器的约定
C++调C: 一种更优雅的写法
- 在实现C头文件时主动对C++提供兼容
- C++调用时无感知
#ifdef __cplusplus
extern "C" {
#endif
int add(int x, int y);
#ifdef __cplusplus
}
#endif
2. C中调用C++函数
- 你可以将C++库封装成C接口,使得C代码可以调用C++类和方法。关键在于使用extern "C"来防止名称修饰,并使用C结构体来包装C++类的实例。
代码实现
#ifdef __cplusplus
extern "C" {
#endif
typedef struct MyClassWrapper MyClassWrapper;
MyClassWrapper* MyClass_create();
int MyClass_add(MyClassWrapper* wrapper, int a, int b);
void MyClass_destroy(MyClassWrapper* wrapper);
#ifdef __cplusplus
}
#endif
总结
- 主要用extern "C" 来解决C++与C互相调用函数时名称修饰的问题。