语言链接性
语言链接性
extern "C" — C/C++ 混合链接
extern "C" 告诉 C++ 编译器用 C 的链接方式(不做名称修饰 name mangling)来处理函数。
为什么需要它:
C++ 编译器会把函数名改成带类型信息的复杂符号(如 void foo(int) → _Z3fooi),而 C 编译器保持原名 foo。混用时就找不到符号了。
用法:
// 单个函数
extern "C" void foo(int x);
// 多个函数
extern "C" {
void foo(int x);
int bar(float y);
}头文件兼容写法(C/C++ 通用):
#ifdef __cplusplus
extern "C" {
#endif
void my_func(int x);
#ifdef __cplusplus
}
#endif__cplusplus 宏只在 C++ 编译时定义,这样头文件 C/C++ 都能用。
注意:
extern "C"函数不能重载(C 没有重载)- 不能用于普通类成员函数(
static成员可以)