当前位置:首页 > 单片机 > 小麦大叔
[导读]经常在C语言的头文件中看到下面的代码: #ifdef __cplusplus extern "C" { #endif // all of your legacy C code here #ifdef __cplusplus } #endif 这通常用于C++和C混合编程的时候,为了防止C++的编译器在编译C文件的时候出现错误; 众所周知,C++可以进行


经常在C语言的头文件中看到下面的代码:

#ifdef __cplusplus
extern "C" {
#endif

// all of your legacy C code here

#ifdef __cplusplus
}
#endif

这通常用于C++C混合编程的时候,为了防止C++的编译器在编译C文件的时候出现错误;
众所周知,C++可以进行函数名重载,但是C则没有这种功能,那这和extern "C"又有什么关系呢?
先看下面这个表格,如下所示;

语言 描述
C 函数名可以作为唯一ID代码段的程序建立联系
C++ 因为重载的关系,函数名符号会被破坏,从而会根据函数的参数不同而重新生成函数符号

未添加 extern "C"

test.h

#ifndef TEST_H
#define TEST_H

void foo1(void);
void foo2(void);
void foo3(int i);

#endif

test.c


void foo1(void){}
void foo2(void) {}
void foo3(int i){}

int main(int argc,char** argv){
 
 foo1();
 foo2();
 foo3(1); 
 return 0;
}

编译这两个文件,生成test.o文件,通过objdump查看函数符号;

g++ -c test.c test.h
objdump -t test.o

可以看到函数符号已经被编译器修改了;

添加extern "C"

test.h

#ifndef TEST_H
#define TEST_H

#ifdef __cplusplus
extern "C" {
#endif
void foo1(void);
void foo2(void);
void foo3(int i);

#ifdef __cplusplus
}
#endif

#endif

test.c

#ifdef __cplusplus
extern "C" {
#endif
void foo1(void){}
void foo2(void) {}
void foo3(int i){}
#ifdef __cplusplus
}
#endif

int main(int argc,char** argv){
 
 foo1();
 foo2();
 foo3(1); 
 return 0;
}

编译这两个文件,生成test.o文件,通过objdump查看函数符号;

g++ -c test.c test.h
objdump -t test.o

这时候函数符号是正确的;

extern "C" 是告诉C++的编译器不要打我这些C函数的主意。

现成轮子OSAL操作系统抽象层的移植

简易PID算法的快速扫盲

一招教你单片机固件快速瘦身

一文教你搞懂C语言的Q格式

基础知识 | hex文件格式详解


—— The End —




免责声明:本文内容由21ic获得授权后发布,版权归原作者所有,本平台仅提供信息存储服务。文章仅代表作者个人观点,不代表本平台立场,如有问题,请联系我们,谢谢!

本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭