What is the static initialisation order fiasco?
Short answer: Global and static objects with dynamic initialisation (constructors that run before main) in different translation units are initialised in an unspecified order. If one global's constructor uses another global defined in a different .cpp file, it may run before that object is constructed and use garbage. On embedded systems, there is a second problem: global constructors run from start-up code, possibly before clocks, memory (external SDRAM) or peripherals are initialised.
// uart.cpp
Uart debug_uart(USART2, 115200); // constructor configures hardware
// logger.cpp
Logger logger(debug_uart); // constructor writes a banner through debug_uart
// if logger is constructed first, it uses an unconstructed Uart → undefined behaviour
Fixes
| Technique | How |
|---|---|
| Construct on first use | Uart &debug_uart() { static Uart u(USART2, 115200); return u; } — initialised the first time the function runs (thread-safe "magic statics" in C++11; with -fno-threadsafe-statics you must ensure first use from one context) |
constexpr / constinit constructors |
objects initialised statically at compile time have no order problem |
| Explicit initialisation | globals with trivial constructors plus an init() called from main in a defined order, after the clock and board setup |
| Placement new into static storage | construct objects explicitly in main (see the placement new question) |
| Keep globals in one translation unit | order within one file is the definition order |
Embedded advice: keep global constructors trivial (no hardware access), initialise hardware explicitly from main in a documented order, and check that the start-up code actually runs __libc_init_array (otherwise global constructors never run at all, a common bug with custom start-up files). Destruction order at exit is the reverse, which rarely matters in firmware that never exits.