理解 extern "C"

extern "C"是为了让代码按照C的方式编译,链接。

$ cat 1.h

#ifdef __cplusplus
extern "C" {
#endif
void foo(void);
#ifdef __cplusplus
};
#endif
$ cat 1.cpp 
#include "1.h"
void foo(void)
{
}
$ g++ 1.cpp -c
$ objdump  -t 1.o | grep foo
00000000 g     F .text	00000006 foo

可见,1.cpp确实是按照C链接的。

如果去掉 extern "C",那么 foo默认将按照 C++ 链接方式:

$ objdump  -t 1.o | grep foo
00000000 g     F .text	00000006 _Z3foov
$ cat 2.cpp 

extern void foo(void);
int main(void)
{
	foo();
	return 0;
}
$ g++ 2.cpp  -c
$ objdump  -t 2.o | grep foo
00000000         *UND*	00000000 _Z3foov

2.cpp期望的是 C++链接方式的foo.因此,这个时候,会有link error:

$ g++ 2.cpp  1.o  
/tmp/cc1kZrnB.o: In function `main':
2.cpp:(.text+0x12): undefined reference to `foo()'
collect2: error: ld returned 1 exit status

解决方法是声明一个 extern "C"的 foo函数(可以通过 include 1.h实现):

$ cat 2.cpp 

#include "1.h"
int main(void)
{
	foo();
	return 0;
}

$ objdump  -t 2.o | grep foo
00000000         *UND*	00000000 foo

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值