extern “C“ 浅析

本文详细讲解了C++调用C语言函数时遇到的编译错误,介绍了两种解决方法:方法一是使用externC修饰,方法二是通过在C语言头文件添加特定C++编译指示。最后总结了推荐使用方法二以简化多函数声明的处理。

// test.h文件
#include <stdio.h>
void show();	// show声明
// test.c文件
#include "test.h"
void show()
{
	printf("hello world!\n");
}

编译错误

c++调用c语言函数编译出错
// cpp文件
#include <iostream>
#include "test.h"

int main()
{
	//show();	// 如果此行不注释掉,编译会报错	// show_v();

	//报错原因:c++中有函数重载,编译器会修饰函数名,但是show是c语言文件,因此链接阶段失败。

	return 0;
}

解决方法一

extern "C" void show();
// test.h文件
#include <stdio.h>
void show();	// show声明
// test.c文件
#include "test.h"
void show()
{
	printf("hello world!\n");
}
// cpp文件
#include <iostream>
//#include "tset.h"  
using namespace std;

// 告诉编译器,show函数用C语言的方式链接
extern "C" void show();	// 上方#include ”test.h"不需要

int main()
{
	show();	

	return 0;
}

解决方法二 ★

一般在C语言文件的头文件(test.h文件)中添加下面六行代码
// ...头文件
// #include <stdio.h>等

#ifdef __cplusplus
extern "C" {
#endif 

// ......中间为每个函数的函数声明

// 添加在头文件底部
#ifdef __cplusplus
}
#endif
// test.h文件
#include <stdio.h>
#ifdef __cplusplus	// 两个下划线 _ _ cplusplus
extern "C" {		// 大写的C
#endif 

void show();	// show声明
void show1();
void show2();

#ifdef __cplusplus
}
#endif
// test.c文件
#include "test.h"
void show()
{
	printf("hello world!\n");
}
void show1()
{
	printf("1hello world!\n");
}
void show2()
{
	printf2("1hello world!\n");
}
// cpp文件
#include <iostream>
#include "test.h"

int main()
{
	show();
	show1();
	show2();

	return 0;
}

总结

一般采用方法二,这样无论多少个函数声明,只需要在C语言头文件中添加六行代码即可。(方法一需要每一个C语言函数声明都添加extern “C”,太麻烦)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值