See also http://stackoverflow.com/questions/211237/c-static-variables-initialisation-order
For gcc use init_priority:
http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
Works across different translation units. So your code would read:
Foo* Foo::singleton __attribute__ ((init_priority (2000))) = new Foo();
Bar* Bar::singleton __attribute__ ((init_priority (3000))) = new Bar();
I don't have gcc handy right now so I can't verify this, but I have used it before.
The other simpler and more portable solution is to avoid static initialization, and explicitly create the singletons in order at some well defined place within main.
// Nothing in static area
void main(void)
{
// Init singletons in explicit order
{
Foo* Foo::singleton = new Foo();
Bar* Bar::singleton = new Bar();
}
// Start program execution
...
}
Remember, things will get just as gnarly with singletons on the way out of the program as well, so its often better to make it explicit.