extern 是 C++ 中一个非常重要的存储类说明符,它的核心作用 是声明一个变量或函数是在别处定义的(通常是在另一个源文件或更早的代码位置),从而告诉编译器:"这个东西存在,它的定义不在我这里,别报错,链接时会找到它。"简单来说,extern 主要解决 C++ 项目中的跨文件全局变量/函数共享 和与 C 语言混合编程两大问题。
1. 跨文件共享全局变量/函数
在 C++ 中,全局变量默认具有外部链接性,但如果你想在 fileA.cpp 中定义,在 fileB.cpp 中使用,就必须在 fileB.cpp 中用 extern 声明它。
cpp
// File: globals.h
extern int g_score; // 声明(不定义)
void printScore();
cpp
// File: globals.cpp
#include "globals.h"
int g_score = 100; // 定义(分配内存)
void printScore() {
std::cout << g_score;
}
cpp
// File: main.cpp
#include "globals.h"
int main() {
g_score = 200; // 可以修改
printScore(); // 输出 200
return 0;
}
2. 让 C++ 调用 C 语言代码
C++ 编译器为了支持函数重载,会将函数名编译成复杂符号(如 func 变成 _Z4funcv)。而 C 语言没有重载,符号名就是函数名本身。所以如果不加 extern "C",C++ 链接器会去找修饰后的符号名,而 C 编译的 .o 文件里只有原始名,导致链接错误。
cpp
// 假设这是 C 语言提供的库(无法修改源码)
// my_c_library.c
void print_hello() { printf("Hello from C"); }
// 在 C++ 中使用时,必须用 extern "C" 包裹声明
extern "C" {
#include "my_c_library.h" // 或者直接声明
void print_hello();
}
int main() {
print_hello(); // 正确调用 C 函数
return 0;
}
3. 改变 const 常量的默认链接性
在 C++ 中,顶层 const 全局变量默认具有"内部链接性"(即仅在当前文件有效)。如果你想让 const 变量跨文件共享,必须加上 extern。
cpp
// File: config.cpp
extern const int MAX_SIZE = 1024; // 必须加 extern 才能外部可见
// File: main.cpp
extern const int MAX_SIZE; // 声明
int arr[MAX_SIZE]; // 使用