Search⌘ K

Solving the Static Initialization Order Fiasco

Understand the static initialization order fiasco, a common issue with static variables across translation units in C++. Learn how to use C++20's consteval and constinit keywords to guarantee compile-time initialization and prevent runtime crashes. Discover legacy solutions like lazy initialization and thread-safe statics, and how modern C++20 features improve program safety and predictability.

According to the FAQ at isocpp.org, the static initialization order fiasco is “a subtle way to crash your program”. The FAQ continues: “The static initialization order problem is a very subtle and commonly misunderstood aspect of C++.”

Before I continue, I want to make a short disclaimer. Dependencies on variables with static storage duration (short statics) in different translation unitsA translation unit is the source file after processing of the C preprocessor. The C preprocessor literally includes the header files using ‘include’ directives, performs conditional inclusion with directives such as ‘ifdef’, or ‘ifndef’, and expands macros. The compiler uses the translation unit to create an object file. are, in general, a code smell and should be a reason for refactoring. Consequently, if you follow my advice to refactor, you can skip this section.

Static initialization order fiasco

Static variables in one translation unit are initialized according to their definition order.

In contrast, the initialization of static variables between ...