跨翻译单元访问 const 变量
在 C++ 中,const 变量对其他翻译单元隐式隐藏。有可能阻止这种情况吗?
In C++, const
variables are implicitly hidden from other translation units. Is is possible to prevent that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,在定义前加上
extern
例如。Yes, prefix the definition with
extern
eg.它可以通过
extern
关键字来实现:这样做的效果是,如果
中常量的值发生变化,您将不需要重新编译
,但同时您失去了在b
ab.cpp
中使用x
作为编译时常量的能力(即您将无法编写int 数组[x];
)。如果没有非常充分的理由,我宁愿在头文件中定义常量并将其包含在所有需要它的翻译单元中;
每次更改时,您都必须重新编译依赖于常量的所有翻译单元,但您将能够在编译时在所有翻译单元中使用它。这种方法的局限性在于,如果更改常量并且仅重新编译某些翻译单元,则常量的值将不一致(这违反了 ODR)。
It can be achieved by means of the
extern
keyword:The effect this will have is that you will not need to recompile
b
if the value of the constant changes ina
, but at the same time you loose the ability to usex
as a compile time constant insideb.cpp
(i.e. you will not be able to writeint array[x];
).If there isn't a very strong reason for this, I would rather have the constant defined in a header file and included in all translation units that require it;
You will have to recompile all translation units that depend on the constant with each change, but you will be able to use it at compile time in all translation units. The limitation of this approach is that if you change the constant and only recompile some of the translation units, the value of the constant will be inconsistent (this is a violation of the ODR).
使用
extern
关键字:这会强制变量具有外部链接。
对于命名空间范围的变量,这通常是默认值,您可以使用静态(或者更好的是匿名命名空间)来强制内部链接。
在我阅读您的问题并尝试之前,我实际上并不知道名称空间范围
const
变量默认具有内部链接,所以感谢您。每天学习新东西!Use the
extern
keyword:This forces the variable to have external linkage.
For namespace-scope variables this is usually the default, and you'd use
static
(or, better, an anonymous namespace) to force internal linkage.I didn't actually know that namespace-scope
const
variables have internal linkage by default until I read your question and tried it out, so thanks for that. Learn something new every day!