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