I have a code:
a.h
...
namespace X
{
const std::string Foo = "foo";
inline std::string getFoo()
{
return Foo;
}
}
...
a.cpp:
#include "a.h"
...
namespace X
{
const string Default_Foo = getFoo();
}
...
Of course there are more files in a project that include a.h
The program results a segfault in start. Investigation showed that:
- Several copies of Foo are created in the program
bash-4.2# nm -oC a.out | grep Foo a.out:3c162c50 b X::Foo a.out:3c162990 b X::Foo a.out:3c1641b0 b X::Foo
2.During initialization Default_Foo calls getFoo(), which does not take the already initialized Foo from a.cpp compilation unit, but instead it takes Foo from another compilation unit, which is by chance, is not initialized yet. This clearly results in a segfault.
Can someone give me a reasoning to such a behavior? What is the best defense strategy against such problems in future?
Finally what I am the most curious about is why getFoo() uses Foo from another compilation unit.