C

extern "C"

kokomi
2025-03-02 / 0 评论 / 2 阅读 / 正在检测是否收录...

.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,这样ccpp文件都可以顺利调用

#ifdef __cplusplus
extern "C"
#endif

    ...
    // 函数声明
    ...
    
#ifdef __cplusplus
}
#endif
0

评论 (0)

取消