简体   繁体   中英

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. 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.

So far I have the following which works:

File0.h

#pragma once

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

File0.cpp

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

Source1.cpp

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

Source2.cpp

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

With extern how do I know when the value has been initialized?

With extern how do I know when the value has been initialized?

You don't. That is known as the static initialization order 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. They are constant expressions as well, just like a macro will produce.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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