c++ - 我应该将关键字 `extern` 添加到常量的定义中以在源文件之间共享吗?

标签 c++ constants extern

在“C++ Primer, Fifth Edition”第 95 页。谈论常量。他说:

Sometimes we have a const variable that we want to share across multiple files but whose initializer is not a constant expression. In this case, we don’t want the compiler to generate a separate variable in each file. Instead, we want the const object to behave like other (non const) variables. We want to define the const in one file, and declare it in the other files that use that object.

To define a single instance of a const variable, we use the keyword extern on both its definition and declaration(s):

// file_1.cc defines and initializes a const that is accessible to other files.

extern const int bufSize = fcn();

// file_1.h

extern const int bufSize; // same bufSize as defined in file_1.cc

我不确定的是最后一段;我从 bufsize 的定义中删除了 extern 但它没问题并且可以从其他文件访问?!

const int bufSize = fcn(); // without keyword extern

为什么他说我们应该在 bufsize 的声明和定义中添加关键字 extern 以便可以从其他文件访问,但我猜是 extern声明中足够了吗?

感谢您的帮助。

最佳答案

你是正确的,在 cpp 文件中不需要 extern

首先,您需要了解什么是声明和定义。您的 bufSize 需要在它使用的每个翻译单元中进行声明,并且在您的程序中有一个单独的定义。那么让我们看看 .h 文件中有什么:

extern const int bufSize;

这是const int 变量的有效声明。这里没有混淆。

现在您需要一个定义,它会转到一个 .cpp 文件,并且您需要确保它存在于整个程序的一个单独位置,否则您将违反 ODR - 单一定义规则。这是您目前拥有的:

extern const int bufSize = fcn();

这是一个有效的定义,因为任何带有 extern 存储类和初始值设定项的声明都是一个定义。然而,

const int bufSize = fcn();

也是一个定义。通过前面声明的 extern,这个定义有一个外部链接——这意味着,它可以从其他翻译单元访问(没有它,命名空间范围内的 const int bufSize 将有内部联系)。

底线 - 示例中的 extern 不会影响编译器行为,但会提醒正在阅读代码的人该变量具有外部链接(因为从这一行看不出来)。

进一步阅读:

https://en.cppreference.com/w/cpp/language/definition

https://en.cppreference.com/w/cpp/language/storage_duration

关于c++ - 我应该将关键字 `extern` 添加到常量的定义中以在源文件之间共享吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54336380/

相关文章:

c++ - n 个多项式的最大线性独立子集

c++ - 为多个平台构建时如何使用 hudson

c++ - 奇怪的未声明的变量编译器错误

java - Android 常量存放在哪里?

C++ 外部对象数组

c - 使用 const 外部值作为非常量外部值是否安全?

c - 在函数内部使用具有相同参数名称的 extern

c++ - 如何摆脱 Djinni 生成的不必要函数 - ToString (in Java)/Description (in Objc)?

java - Java 编译器是否包含字符串常量折叠?

c - 字符串文字是常量吗?