On 2008-09-30 09:02:29 -0400, Zeppe
<
[email protected]> said:
Well, yes, main is in some ways special. But we were talking
about initialization, and the rule, once again, is that static
objects must be initialized before the first entry into any
function defined in the same translation unit. It doesn't
matter whether the name of that function is main, foo, bar, or
billy. And it doesn't matter whether main is also in that
translation unit.
What the current standard says is that "if the initialization is
deferred to some point in time after the first statement of
main, it shall occur before the first use of any function or
object defined in the same translation unit as the object to be
initialized."
The standard doesn't really define what it means by use, which
makes it rather hard to figure out what is really meant. (Is
taking the address of an object "use"? What if the address is
used to initialize a static pointer?) On the whole, it opens
the door to possible cycles, in which the compiler is required
to initialized A before B, and B before A.
The issue is further muddled by the statement in the current
draft that "Non-local objects with static storage duration are
initialized as a consequence of program initiation." Again,
it's not really too clear what this means, but "program
initiation" certainly suggests "before the first statement in
main".
And of course, no compiler actually does defer the
initialization until after main. In practice, several
widespread idioms count on it, and no compiler would dare to
break them. So in practice, it's safe to say that
initialization does occur before the first statement in main,
even if the standard explicitly gives an implementation other
alternatives.
[...]
That's not required by the standard. The rule is as I've set out above.
That's a provision for dynamically linked libraries, which can be
loaded on demand, and don't initialize their statics until they are
loaded.
And which also violate the phases of translation, and so are
"undefined behavior" as far as the standard is concerned.
(Obviously, implementations do define this behavior. Just as
obviously, if you're using dynamic linking, you turn to the
guarantees given by your implementation.)