简体   繁体   English

在命名空间c ++中正确声明extern变量

[英]Correctly declaring extern variable in a namespace c++

I have some const variables that I would like the values of to be shared between multiple source files. 我有一些const变量,我希望在多个源文件之间共享值。 I would also like the variable's scope to be limited to a namespace. 我还希望变量的范围限于命名空间。 I am unsure of the best/correct way to do this? 我不确定最好/正确的方法吗?

I could use a #define but want to have the type safety. 我可以使用#define但希望类型安全。

So far I have the following which works: 到目前为止,我有以下工作:

File0.h File0.h

#pragma once

namespace Namespace1
{
   extern const int variable1;
   extern const int variable2;
}

File0.cpp File0.cpp

const int Namespace1::variable1 = 10;
const int Namespace1::variable2 = 10;

Source1.cpp Source1.cpp

#include "File0.h"
int result1 = Namespace1::variable1 + Namespace1::variable2;

Source2.cpp Source2.cpp

#include "File0.h"
const int result2 = Namespace1::variable1 + Namespace1::variable2;

With extern how do I know when the value has been initialized? 使用extern我如何知道值何时初始化?

With extern how do I know when the value has been initialized? 使用extern我如何知道值何时初始化?

You don't. 你没有。 That is known as the static initialization order fiasco . 这被称为静态初始化顺序fiasco Initialization of namespace scope static objects in different translation units is done in an unspecified order. 在不同的翻译单元中初始化命名空间范围静态对象是以未指定的顺序完成的。 If one static object depends on another object in a different translation for its initialization, the behavior is undefined. 如果一个静态对象依赖于另一个转换中的另一个对象进行初始化,则该行为是未定义的。

Even with simple integers, this catastrophe can occur. 即使使用简单的整数,也可能发生这种灾难。 Since your intention is to avoid macros (a worthy goal) you can just define those constants in the header: 由于您的目的是避免宏(一个有价值的目标),您可以在标头中定义这些常量:

namespace Namespace1
{
    const int variable1 = 10;
    const int variable2 = 10;
}

That will not be a one-definition-rule violation, since the C++ standard (even in 2003) allows for such integral constants to be defined in multiple translation units by making them implicitly have internal linkage. 这不会违反单定义规则,因为C ++标准(即使在2003年)允许通过使它们隐式地具有内部链接来在多个转换单元中定义这样的积分常量。 They are constant expressions as well, just like a macro will produce. 它们也是常量表达式,就像宏会产生的一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM