Is the static initialization of global variables completed before `main()`? Is the static initialization of global variables completed before `main()`? multithreading multithreading

Is the static initialization of global variables completed before `main()`?


The standard says that all objects are initialized in the same translation unit (aka object file which corresponds to a single source file) before any function is called in that translation unit. In your example, it looks like they are in the same file, so a will be initialized before main() is called.

The standard is allowing lazy initialization to occur in the event that a DLL is loaded at run time. If you allow run-time linkage of your code, you can't say that everything is initialized before main().


Yes, if you had a object outside a function such as

Foobar foo;

If Foobar has a constructor, it would nominally run before main(). Likewise its destructor runs after main() exits. I would be hesitant to make use of this feature though. One issue, if you have these sort of objects in multiple files the order of creation is indeterminate.