网站首页 > 文章精选 正文
13.1 在 CPP 文件中使用 extern “C”
show.h 文件 // show 函数声明
===============================
#pragma once
#include <stdio.h>
#include <stdlib.h>
void show();
****************************************************************************************
show.c 文件 // show 函数实现
===============================
#include "test.h"
void show()
{
printf("hello world\n");
}
****************************************************************************************
test.cpp 文件
===============================
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include "test.h"
// extern "C" void show(); // extern "C" 用途: 用来在 CPP 中调用 C 文件中函数
void test()
{
show();
}
int main()
{
test(); // 如果没有 extern "C" void show(); 会报错
system("pause");
return 0;
}
报错原因: C++ 存在函数重载机制,会修饰 show()函数名(比如有可能是 _Z4showv ),再去调用
因此在链接时候,在 test.c 文件中 只找到 show(),而不是_Z4showv,无法链接成功
解决:
在 test.cpp 文件 的全局范围内 加 一句话
extern "C" void show(); // 告诉编译器 show 函数 在别的文件中,而且是需要用 C 方式去链接
13.2 在头文件中使用 extern “C”
注意: 在 CPP 文件中使用 extern “C”, 有弊端
试想: 如果 .c 文件中使用了多个函数,则需要在.cpp 文件中使用多次 extern "C" ,非常麻烦
解决: 在 C 的头文件 .h 中使用 extern "C" ,一次性解决(一共 6 行)
例如:
将 13.1 中的 show.h 文件修改为
#if __cplusplus
extern "C"{
#endif
#pragma once
#include <stdio.h> 原 头文件 和 函数声明
#include <stdlib.h>
void show();
#ifdef __cplusplus
}
#endif
猜你喜欢
- 2025-06-28 程序员C/C++你不得不看的27个优化建议
- 2025-06-28 [c++面试题]数据库中的outer join, 你了解吗?
- 2025-06-28 开机弹出 C++ Runtime Library: Assertion failed窗口解决方法
- 2025-06-28 C++调用外部程序传递用户名密码登录
- 2025-06-28 C++编程:标准库visit和variant用法
- 2025-06-28 C/C++编程推荐学习顺序和书籍(c++编程需要学多久)
- 2025-06-28 c/c++如何避免头文件被多次包含(c语言避免头文件重复定义)
- 2025-06-28 C++程序编译之谜(一)——多文件编译的奇怪现象
- 2025-06-28 C++20 香不香?从四大新特性看起(c++20支持)
- 最近发表
- 标签列表
-
- newcoder (56)
- 字符串的长度是指 (45)
- drawcontours()参数说明 (60)
- unsignedshortint (59)
- postman并发请求 (47)
- python列表删除 (50)
- 左程云什么水平 (56)
- 计算机网络的拓扑结构是指() (45)
- 编程题 (64)
- postgresql默认端口 (66)
- 数据库的概念模型独立于 (48)
- 产生系统死锁的原因可能是由于 (51)
- 数据库中只存放视图的 (62)
- 在vi中退出不保存的命令是 (53)
- 哪个命令可以将普通用户转换成超级用户 (49)
- noscript标签的作用 (48)
- 联合利华网申 (49)
- swagger和postman (46)
- 结构化程序设计主要强调 (53)
- 172.1 (57)
- apipostwebsocket (47)
- 唯品会后台 (61)
- 简历助手 (56)
- offshow (61)
- mysql数据库面试题 (57)