在.h
文件中(函数的实现在对应的.c
文件中),经常会看到这样的代码:
#ifdef __cplusplus
extern "C" {
#endif
...
函数声明
...
#ifdef __cplusplus
}
#endif
这样做的原因是什么呢?首先我们要弄清楚C++
和C
编译的区别,以 fun
函数为例:
// fun.h中声明
int fun(int a, int b);
// fun.c中实现
# include "fun.h"
int fun(int a, int b){
return a + b;
}
fun
函数在C
的编译中会被编译成_fun
,在C++
中会被编译成_fun_int_int
;(C
对函数的编译在转换成汇编代码的时候只取函数名,而C++
是函数名加上参数类型;因此C++
支持函数的重载,而C
不支持函数的重载);- 如果
cpp
文件调用了.h
(在.c文件中实现) 文件中的fun
函数,编译链接时会按照_fun_int_int
来找,就会找不到fun
函数; - 如果加上
extern "C"
,C++
就会按照_fun
来找fun
函数,就可以找到该函数;
因此解决方法有以下两种(刚好对应extern "c"
的使用场景):
1、在cpp
文件中使用extern "c"
声明使用到的c
函数
// cpp文件中
extern "C"{
// 用extern "C"声明fun.cpp文件中的函数,以至于可以在cpp文件中使用
extern int fun(int a, int b);
}
2、在.h
文件中加上extern "c"
(推荐)extern "C"
只是C++
的关键字,不是 c
的,c
不认识extern "c"
,所以需要加上ifdef __cplusplus
,这样c
和cpp
文件都可以顺利调用
#ifdef __cplusplus
extern "C"
#endif
...
// 函数声明
...
#ifdef __cplusplus
}
#endif
评论 (0)