定义的地方也需要就上 extern,否则编译时就会找不到链接,报错:ld: symbol (s) not found for architecture arm64。我之前在 vscode 直接执行 test.cpp,即便定义的地方不加 extern 也不会报错,这应该是 vscode 做了处理,在命令行编译就会遇到:g++ test.cpp test1.cpp -o test。
test1.cpp
externconstint a =1;
externconstint b =2;
test.cpp
#include<iostream>
usingnamespace std;
// extern int a; error: edeclaration of 'a' with a different type: 'int' vs 'const int'
externconstint a;
// extern const int b = 2; error: Redefinition of 'b'
intmain(){
cout << a << endl;// 1
// extern const int a = 3; error: 'extern' variable cannot have an initializer
int a =3;
cout << a << endl;// 3
externconstint 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'