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

被折叠的 条评论
为什么被折叠?



