c++ - 使用 "extern"关键字而没有 #include "file.h"

标签 c++ include extern

现在我读了斯蒂芬普拉塔关于 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/

相关文章:

c - 当我们可以以相同的成本获得全局变量时,静态局部变量有什么用?

c - linux内核源代码错误?

c++ - 内联函数 C++ 的 undefined reference

c++ - 包裹一个数字?

编译时的 C++ 展开循环

c++ - 出现频率

c++ - 从 C++ 调用 Lua 表中的函数

c - 包含二进制文件作为常量数组

Java:针对包含另一个 xsd 的 xsd 进行字符串 xml 验证

c++ - h和hpp问题,包含顺序错误