2

I encountered something very strange today.

I have util.hpp, and util.cpp to share some const strings with the whole project.

In util.hpp:

extern const string stringOne;

static string stringTwo = "Foo" + stringOne;

In Util.cpp:

const string stringOne = "One";

There are many places in the codebase which uses stringTwo, and sometimes, stringTwo shows up with the correct value: "FooOne", and sometimes, it shows up as "Foo".

This is so strange, and I think it is a C++ compilation bug.

pm100
  • 48,078
  • 23
  • 82
  • 145
Lin Jia
  • 21
  • 1
  • Please put your question in proper format – M. Twarog Feb 13 '22 at 19:35
  • 2
    Evaluation order of static variables is undefined. If you need them in a particular order, then write an explicit initializer function – Silvio Mayolo Feb 13 '22 at 19:36
  • read in your book what is meaning of `static` when used in global scope, then everything will be clear what is going on. – Marek R Feb 13 '22 at 19:42
  • Globals in files that happen to be linked after Util.cpp will see the initialization, those linked before will not. Order of .cpp files is up to the linker, in practice more or less random. – BoP Feb 13 '22 at 19:45
  • As you notice from the duplicate questions, your finding has even a name: *static initialization order fiasco*. It is called **fiasco** for a reason. – prapin Feb 13 '22 at 20:20

0 Answers0