Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correctly declaring extern variable in a namespace c++

Tags:

c++

c++03

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?

like image 482
Alex Angell Avatar asked Mar 06 '23 11:03

Alex Angell


1 Answers

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.

like image 152
StoryTeller - Unslander Monica Avatar answered Mar 15 '23 22:03

StoryTeller - Unslander Monica