栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

cpp无法调用c代码(重载机制)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

cpp无法调用c代码(重载机制)

当main.c test.c 都是纯c文件编译和连接没问题正常运行

main.c

#include 
#include 
#include "test.h"

int main()
{
    show();
    // printf("jshdfg");
    system("pause");
}

test.c

#include 
#include "test.h"

void show()
{
    printf(" show executing !n");
}

test.h

#include 

void show();

运行结果

生成解决方案成功

运行成功

当main.cpp是cpp文件时

#include 
using namespace std;
#include "test.h"

int main()
{
    show();
    // printf("jshdfg");
    system("pause");
}

编译成功 语法没错

 生成解决方案出错,链接时出错

 

 因为cpp有重载机制会把show()定义为符号 如showv (v就代表形参列表为空),但是c语言没有重载机制。所以cpp文件要使用c文件中的函数时要注明该函数在c文件中,要加上

extern "C" void show();

main.cpp改为(注意此时不用在include "test.h" 否则重定义了)

#include 
using namespace std;
//include "test.h"
extern "C" void show();

int main()
{
    show();
    system("pause");
}

可以正确执行了

 上述规则等于告诉了编译器show()函数应该按c语言的规则来进行链接

但是每个c文件中的函数都要在main函数里

extern "C" 返回值类型 函数名(形参列表);

就太麻烦了

这种声明函数是c函数应该在.h文件中提前声明号

test.h

#ifdef __cplusplus
extern "C" {
#endif // __cplusplus

#include 

	void show();
	//void show1() 
	//void show2() 
	//void show3()... 

#ifdef __cplusplus
}
#endif // __cplusplus

这样就同时声明了多个函数是c语言函数了,#ifdef __cplusplus 在cpp文件调用时自动extern "C"

main.cpp (包含头文件即可,不用使用关键字extern了)

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/849148.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号