extern 的作用是什么呢?对于 C++ 中的全局变量,作用域是当前文件,那么当其他文件想要访问的时候,就可以使用 extern 关键字。extern 用于指示变量或函数的定义在另一个源文件中,并在当前源文件中进行声明。

# 声明全局变量

对于另一个文件中定义的变量,在当前文件全局区域用 extern 链接过去,但是不能再次定义。如果局部区域没有 extern 该变量,那么可以再次声明定义相同变量。另外 extern 修饰的变量的值也是可以被修改的。

test1.cpp
int a = 1;
int b = 2;
test.cpp
#include <iostream>
using namespace std;
extern int a;
// extern int b = 2; error: Redefinition of 'b'
int main() {
  cout << a << endl; // 1
  // extern int a = 3; error: 'extern' variable cannot have an initializer
  int a = 3;
  cout << a << endl; // 3
  extern int b;
  cout << b << endl; // 2
  // int b = 4; error: Non-extern declaration of 'b' follows extern declaration
  b = 4;
  cout << b << endl; // 4
}

# 修饰常量全局变量

定义的地方也需要就上 extern,否则编译时就会找不到链接,报错:ld: symbol (s) not found for architecture arm64。我之前在 vscode 直接执行 test.cpp,即便定义的地方不加 extern 也不会报错,这应该是 vscode 做了处理,在命令行编译就会遇到:g++ test.cpp test1.cpp -o test。

test1.cpp
extern const int a = 1;
extern const int b = 2;
test.cpp
#include <iostream>
using namespace std;
// extern int a; error: edeclaration of 'a' with a different type: 'int' vs 'const int'
extern const int a;
// extern const int b = 2; error: Redefinition of 'b'
int main() {
  cout << a << endl; // 1
  // extern const int a = 3; error: 'extern' variable cannot have an initializer
  int a = 3;
  cout << a << endl; // 3
  extern const int b;
  cout << b << endl; // 2
  // const int b = 4; error: Non-extern declaration of 'b' follows extern declaration
  // b = 4; error: Cannot assign to variable 'b' with const-qualified type 'const int'
}