Static Initialization Fiasco - On Purpose
<p>Just for fun, I was investigating the order of dynamic initialization of static objects.
In a file name t.h, I put</p>

<pre><code>struct T {
   static std::vector&lt;std::string&gt; me;
   static int add(std::string s) { me.push_back(s); return me.size(); }
};
</code></pre>

<p>(Plus needed headers for vector and string.)
"std::vector T::me" is in t.cpp.
The file main.cpp prints out the values in T::me:</p>

<pre><code>#include "t.h"
#include &lt;iostream&gt;
using namespace std;

int main()
{
    T::me.push_back("main");
    cout &lt;&lt; "T::me.size()=" &lt;&lt; T::me.size() &lt;&lt; endl;
    for (unsigned i = 0; i&lt;T::me.size(); ++i) {
        cout &lt;&lt; i &lt;&lt; "-" &lt;&lt; T::me[i] &lt;&lt; endl;
    }
    return 0;
}
</code></pre>

<p>next, I create "a.cpp" and put the following in it:</p>

<pre><code>#include "t.h"

int a = T::add("a");
</code></pre>

<p>Do the similar for file b.cpp and c.cpp using "b" and "c" as appropriate.
Compile using g++ *.cpp, then run ./a.out. The order of static initialization from compilation unit to compilation unit is unspecified. In my case it is consistently in reverse alphabetical order. I get:
3 - c
2 - b
1 - a
0 - main</p>

<p>No problems so far.</p>

<p>Now I create u.cpp like a.cpp but using "u". Recompile/rerun, "u" does not show up in the list.</p>

<p>Is it because I never referenced u? I never referenced a,b,c, but I change main:</p>

<pre><code>#include "t.h"
#include &lt;iostream&gt;
using namespace std;

extern int u;

int main()
{
    cout &lt;&lt; "u=" &lt;&lt; u &lt;&lt; endl;
    T::me.push_back("main");
    cout &lt;&lt; "T::me.size()=" &lt;&lt; T::me.size() &lt;&lt; endl;
    for (unsigned i = 0; i&lt;T::me.size(); ++i) {
        cout &lt;&lt; i &lt;&lt; "-" &lt;&lt; T::me[i] &lt;&lt; endl;
    }
    return 0;
}
</code></pre>

<p>The program prints out "u=2", but "u" is not in the list. Shouldn't u have been dynamically initialized <em>before</em> use and, therefore, T::me have been updated to include "u"? I think there should be a better explanation than that u comes after t in the alphabet.</p>
