C语言 extern “C“的作用

在看代码的时候遇到了这个问题。但是可能由于C++编译器版本的原因,我并没有成功地复现出这个问题,索性记录一下问题本身。

extern "C"主要是用于在Cpp文件中调用C的函数。

C++支持函数的重载,但是C不支持。

// CPP中由重载导致的函数魔改
int func(int x) {
   return x*x;
}
double func(double x) {
   return x*x;
}
void my_function(void) {
   int x = func(2); //integer
   double y = func(2.58); //double
}

C++编译器对这些同名不同参的重载函数的处理方法是,改写函数名,把参数信息体现在函数中。

int __func_i(int x){
   return x*x;
}
double __func_d(double x){
   return x*x;
}
void __my_function_v(void){
   int x = __func_i(2); //integer
   double y = __func_d(2.58); //double
}

注意到,这里的函数my_function即使没有重载,它也被魔改了。

当我们在C++代码中使用extern "C"时,C++编译器不会魔改你的函数名,而是按照C的规范进行编译。

extern "C"
{
     #include<stdio.h>    // Include C Header
     int n;               // Declare a Variable
     void func(int,int);  // Declare a function (function prototype)
}

int main()
{
    func(int a, int b);   // Calling function . . .
    return 0;
}

// Function definition . . .
void func(int m, int n)
{
    //
    //
}

上述代码中,extern "C"中包含的func的声明和定义不会被魔改。但是如果没有extern "C"的声明,C++编译器就会对对函数名下手了。

猜你喜欢

转载自blog.csdn.net/weixin_43466027/article/details/131924165