再谈C/C++中的extern “C”

众所周知, C语言头文件中的extern “C”的作用是为了让C++编译器能够调用C编译器产生的二进制代码。由于C++支持函数重载等原因,C++和C编译器产生二进制代码中的函数名字是不一样的。不过,如果直接使用C++编译器来编译带有extern “C”的源代码,生成的代码能直接为C代码使用吗?

    经测试,答案是:可以。

    测试代码如下:

test.h

#ifndef _TEST_H_
#define _TEST_H_

#ifdef __cplusplus
extern "C"
{
#endif

void test();

#ifdef __cplusplus
}
#endif

#endif

test.c

#include "test.h"
#include "stdio.h"

void test()
{
	printf("dddddd");
}

使用g++编译器来编译上述代码:

[root@localhost test]# g++ test.c -c 
[root@localhost test]# nm test.o 
         U printf
00000000 T test
[root@localhost test]#

可以看出,编译产生的代码与使用gcc编译器一致,并且该代码可以被C代码调用:

enter.c

#include "test.h"

int main()
{
	test();

	return 0;
}

[root@localhost test]# gcc enter.c -c
[root@localhost test]# gcc enter.o test.o -o enter
[root@localhost test]# ./enter
dddddd[root@localhost test]#

结论: 使用C++编译器编译带有extern “C”的源文件,产生的代码可以被C代码调用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值