现在我读了斯蒂芬普拉塔关于 C++ 的书,并学习了 extern 关键字及其用法。所以我有一个问题。我可以输入“extern int var a;”吗?不包括定义和初始化这个“a”变量的文件?
#include <iostream>
//#include "vars.h" Not including the file with 'a' variable
using namespace std;
extern int a;
int main()
{
cout << a << endl;
return 0;
}
最佳答案
extern
关键字将表示该变量具有外部链接。
When a name has external linkage, the entity it denotes can be referred to by names from scopes of other translation units or from other scopes of the same translation unit.
来自 https://eel.is/c++draft/basic.link
如果您尝试按原样运行上述代码,您将收到链接器错误
a
未在当前作用域中定义。所以它必须从另一个翻译单元获取它,这可以在链接过程中完成。
关于c++ - 使用 "extern"关键字而没有 #include "file.h",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65690027/