EDIT: Changed example below to one that actually demonstrates the SIOF.
I am trying to understand all of the subtleties of this problem, because it seems to me to be a major hole in the language. I have read that it cannot be prevented by the linker, but why is this so? It seems trivial to prevent in simple cases, like this:
// A.h
extern int x;
// A.cpp
#include <cstdlib>
int x = rand();
// B.cpp
#include "A.h"
#include <iostream>
int y = x;
int main()
{
std::cout << y; // prints the random value (or garbage)?
}
Here, the linker should be able to easily determine that the initialization code for A.cpp should happen before B.cpp in the linked executable, because B.cpp depends on a symbol defined in A.cpp (and the linker obviously already has to resolve this reference).
So why can’t this be generalized to all compilation units. If the linker detects a circular dependency, can’t it just fail the link with an error (or perhaps a warning, since it may be the programmer’s intent I suppose to define a global symbol in one compilation unit, and initialize it in another)?
Does the standard levy any requirements on an implementation to ensure the proper initialization order in simple cases? What is an example of a case where this would not be possible?
I understand that an analogous situation can occur at global destruction time. If the programmer does not carefully ensure that the dependencies during destruction are symmetrical to construction, a similar problem occurs. Could the linker not warn about this scenario as well?
Linkers traditionally just link – i.e. they resolve addresses. You seem to be wanting them to do semantic analysis of the code. But they don’t have access to semantic information – only a bunch of object code. Modern linkers at least can handle large symbol names and discard duplicate symbols to make templates more useable, but so long as linkers and compilers are independent, that’s about it. Of course if both linker and compiler are developed by the same team, and if that team is a big corporation, more intelligence can be put in the linker, but it’s hard to see how a standard for a portable language can mandate such a thing.
If you want to know more about linkers, BTW, take a look at http://www.iecc.com/linker/ – about the only book on an often ignored tool.