extern用于声明全局函数/全局变量/c函数/外部全局函数
1、声明全局函数
// math.cpp - 定义全局函数
int add(int a, int b) { // 全局函数
return a + b;
}
// math.h - 声明全局函数
extern int add(int a, int b); // extern可以省略,但显式写出更清晰
// main.cpp - 使用全局函数
#include "math.h" // 包含声明
int main() {
int sum = add(10, 20); // 调用全局函数
return 0;
}
全局函数可以在任何文件内调用,只能有一个定义,可以有多个声明;
全局函数的定义,可以加extern也可以不加,extern表示显示声明,这个函数的定义在外部,如果在本文件内定义将报错;
调用做法:引用头文件,直接调用;
直接在文件内声明 extern int add(…);则无需引用头文件;链接器根据它的符号表寻找;
2、声明外部全局变量
和全局函数类似,区别是extern不能省略
cpp
// globals.cpp
int global_counter = 0; // 定义全局变量
// main.cpp
extern int global_counter; // 声明外部全局变量
int main() {
global_counter++; // 使用外部变量
return 0;
}
3、指定C语言链接
// 在C++中使用C语言编写的库
extern "C" {
#include "clibrary.h" // C语言头文件
int c_function(int); // C语言函数
}
// 或者
extern "C" int c_function(int); // 单独声明C函数
extern “C” 告诉C++编译器:
“这个函数使用C语言的命名和调用约定,不要进行C++的名称修饰”
方式1:整个头文件包裹在 extern “C” 中
// main.cpp - C++程序
#include <iostream>
extern "C" {
#include "clibrary.h" // 告诉C++:这个头文件里的函数是C风格的
}
int main() {
int result = c_add(10, 20); // 调用C函数
c_print_message("Hello from C++"); // 调用C函数
std::cout << "结果: " << result << std::endl;
return 0;
}
方式2:单独声明每个C函数
// main.cpp
#include <iostream>
// 单独声明C函数
extern "C" int c_add(int a, int b);
extern "C" void c_print_message(const char* message);
extern "C" double c_calculate(double x);
int main() {
int sum = c_add(5, 3);
c_print_message("单独声明方式");
return 0;
}
方式3:条件编译(推荐的标准做法)
// clibrary.h - 改进的C语言头文件
#ifndef CLIBRARY_H
#define CLIBRARY_H
#ifdef __cplusplus
extern "C" { // 如果是C++编译器,添加extern "C"
#endif
// C语言函数声明
int c_add(int a, int b);
void c_print_message(const char* message);
double c_calculate(double x);
#ifdef __cplusplus
} // 结束extern "C"块
#endif
#endif
// main.cpp - C++程序可以直接包含
#include <iostream>
#include "clibrary.h" // 现在可以直接包含,头文件自己处理了extern "C"
int main() {
c_add(10, 20); // 正常工作
return 0;
}
什么情况需要extern c语言?
待补充
854

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



