The C standard says only this:
C11 5.1.2p1
[...]All objects with static storage duration shall be initialized (set to their initial values) before program startup. The manner and timing of such initialization are otherwise unspecified.
and
C11 6.2.4p2-3
2 The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address,33) and retains its last-stored value throughout its lifetime.34) If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.
3 An object whose identifier is declared without the storage-class specifier _Thread_local, and either with external or internal linkage or with the storage-class specifier static, has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.
But... this is further made complicated by the as-if rule, the actual implementation need to do this only as far as observable side effects go.
In fact in Linux for example, one could argue that the variables with static storage duration are initialized and allocated by the compiler and the linker when producing executable file. When the program is run, the dynamic linker (ld.so
) then prepares the program segments so that the initialized data is memory-mapped (mmap
) from the executable image to RAM, default (zero-initialized) data is mapped from zeroed pages.
While the virtual memory is allocated by the compiler, linker and dynamic linker, the actual writable RAM page frames are allocated only when you write to a variable on a page for the first time...
but you do not need to know about this in basic cases. It is as if the memory for variables with static storage duration were allocated and initialized just before main
was entered, even though this is not actually the case.