网站首页 > 基础教程 正文
13.1 在 CPP 文件中使用 extern “C”
show.h 文件 // show 函数声明
===============================
#pragma once
#include
#include
void show();
****************************************************************************************
show.c 文件 // show 函数实现
===============================
#include "test.h"
void show()
{
printf("hello world\n");
}
****************************************************************************************
test.cpp 文件
===============================
#define _CRT_SECURE_NO_WARNINGS
#include
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
#include
void show();
#ifdef __cplusplus
}
#endif
猜你喜欢
- 2025-03-10 extern "C"用法详解
- 2025-03-10 嵌入式C语言基础编程—5年程序员给你讲函数,你真的懂函数吗?
- 03-10extern "C"用法详解
- 03-10嵌入式C语言基础编程—5年程序员给你讲函数,你真的懂函数吗?
- 03-10C++知识点 13:extern“C”
- 03-10go语言text/template标准库
- 03-10Python 的os和shutil包简介
- 03-10前端代码质量-圈复杂度原理和实践
- 03-10近2万字详解JAVA NIO2文件操作,过瘾
- 03-10这两个Python库,轻而易举就能实现MP4与GIF格式互转,太好用了
- 最近发表
- 标签列表
-
- gitpush (61)
- pythonif (68)
- location.href (57)
- tail-f (57)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- css3动画 (57)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- exec命令 (59)
- canvasfilltext (58)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- node教程 (59)
- console.table (62)
- c++time_t (58)
- phpcookie (58)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)