According to the FAQ of isocpp.org is the static initialization order fiasco “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++. “. Today, I write about this very subtle and misunderstood aspect of C++.
My short Disclaimer
Before I continue, I want to make a short disclaimer. Today’s post is about variables with static storage duration and their dependencies. Variables with static storage duration may be global (namespace) variables, static variables, or static class members. In short, I call them static variables. Dependencies on static variables in different translation units are generally a code smell and should be a reason for refactoring. Consequently, if you follow my advice to refactor, you can skip the rest of this post.
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 translation units has a severe issue. When one static variable staticA is defined in one translation unit and another static variable staticB is defined in another, and staticB needs staticA to initialize itself, you end with the static initialization order fiasco. The program is ill-formed because you have no guarantee which static variable is initialized first at run-time (dynamic).
Before discussing the rescue, let me show you the static initialization order fiasco.
A 50:50 Chance to get it Right
What is unique about the initialization of static variables? The initialization of static variables happens in two steps: static and dynamic.
Line (1) declares the static variable staticA. The initialization of staticB depends on the initialization of staticA. staticB is zero-initialized at compile-time and dynamically initialized at run-time. The issue is that there is no guarantee in which order staticA or staticB are initialized. staticA and staticB belong to different translation units. You have a 50:50 chance that staticB is 0 or 25.
To make my observation visible, I change the link order of the object files. This also changes the value for staticB!
What a fiasco! The result of the executable depends on the link order of the object files. What can we do when we don’t have C++20 at our disposal?
Lazy Initialization of static with local scope
Static variables with the local scope are created when used for the first time. Local scope essentially means that the static variable is surrounded in some way by curly braces. This lazy creation is a guarantee that C++98 provides. With C++11, static variables with the local scope are also initialized in a thread-safe way. The thread-safe Meyers Singleton is based on this additional guarantee. I already wrote a post about the “Thread-Safe Initialization of a Singleton“.
Lazy initialization can also be used to overcome the static initialization order fiasco.
staticA is, in this case, static in a local scope (1). Line (2) declares the function staticA, which is used to initialize in the following line staticB. This local scope of staticA guarantees that staticA is created and initialized during run-time when it is the first time used. Changing the link order can, in this case, not change the value of staticB.
Now, I solve the static initialization order fiasco using C++20.
Compile-time initialization of a static
Let me apply constinit to staticA. constinit guarantees that staticA is initialized during compile-time.
(1) declares the variable staticA. staticA (2) is initialized during compile-time. By the way, using constexpr in (1) instead of constinit is not valid because constexpr requires a definition and not just a declaration.
Thanks to Clang 10 compiler, I can execute the program.
As in the case of the lazy initialization with a local static, staticB has the value 25.
C++20 has a few small improvements around Templates and Lambdas. In my next post, I will present which ones.
Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, moon, and Philipp Lenk.
Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, Slavko Radman, and David Poole.
|My special thanks to Embarcadero|
|My special thanks to PVS-Studio|
|My special thanks to Tipi.build|
|My special thanks to Take Up Code|
|My special thanks to SHAVEDYAKS|
I’m happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.
- Embedded Programmierung mit modernem C++ 12.12.2023 – 14.12.2023 (Präsenzschulung, Termingarantie)
Standard Seminars (English/German)
Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.
- C++ – The Core Language
- C++ – The Standard Library
- C++ – Compact
- C++11 and C++14
- Concurrency with Modern C++
- Design Pattern and Architectural Pattern with C++
- Embedded Programming with Modern C++
- Generic Programming (Templates) with C++
- Clean Code with Modern C++
- Phone: +49 7472 917441
- Mobil:: +49 176 5506 5086
- Mail: schulung@ModernesCpp.de
- German Seminar Page: www.ModernesCpp.de
- Mentoring Page: www.ModernesCpp.org
Modernes C++ Mentoring,