C++ global initialization order ignores dependencies?
<p>I think my problem is best described in code:</p>

<pre><code>#include &lt;stdio.h&gt;

struct Foo;

extern Foo globalFoo;

struct Foo {
    Foo() {
        printf("Foo::Foo()\n");
    }

    void add() {
        printf("Foo::add()\n");
    }

    static int addToGlobal() {
        printf("Foo::addToGlobal() START\n");

        globalFoo.add();

        printf("Foo::addToGlobal() END\n");

        return 0;
    }
};

Foo globalFoo;

int dummy = Foo::addToGlobal();

int main() {
    printf("main()\n");

    return 0;
}
</code></pre>

<p>The above prints (with gcc 4.4.3):</p>

<pre><code>Foo::Foo()
Foo::addToGlobal() START
Foo::add()
Foo::addToGlobal() END
main()
</code></pre>

<p>This is what I expect, and seems logical.</p>

<p>However, when I swap the following lines:</p>

<pre><code>Foo globalFoo;
int dummy = Foo::addToGlobal();
</code></pre>

<p>into this:</p>

<pre><code>int dummy = Foo::addToGlobal();
Foo globalFoo;
</code></pre>

<p>the program outputs the following:</p>

<pre><code>Foo::addToGlobal() START
Foo::add()
Foo::addToGlobal() END
Foo::Foo()
main()
</code></pre>

<p>It seems <em>instance methods of <code>Foo</code> are being called using an instance which has not yet been constructed</em>!  Something as simple as moving the declaration of a variable in the global scope is affecting the behaviour of the program, and that leads me to believe (1) the order of initialization of globals is not defined and (2) the order of initialization of globals ignores all dependencies.  Is this correct?  Is it possible to make sure the constructor of <code>Foo</code> is called before initializing <code>dummy</code>?</p>

<p>The problem I am trying to solve is filling a repository of items (a static instance of <code>Foo</code>) statically.  In my current attempt, I am using a macro which (among other things) creates a global variable (in an anonymous namespace to avoid name clashing) whose initialization triggers the static initialization.  Perhaps I'm tackling my problem from the wrong angle?  Is there a better alternative(s)?  Thanks.</p>
