A C++ plugin host crashes before main when a plugin's global registrar inserts into a global registry map; why, and how do you fix it?
answer
- ordered only inside one file
- link order decides in practice
- zero-initialized but not constructed
- construct on first use
- constinit when the value is constant
basics
~20 sDynamic initialization of globals in different translation units is indeterminately ordered, so the registrar can run before the registry map's constructor. Construct the registry on first use inside a function, or constant-initialize it with constinit where its type allows.
solid answer
~40 sEvery static-duration variable is first **zero-initialized** or **constant-initialized**; anything else is **dynamic initialization**, and that is ordered only within one translation unit, by definition order. Across translation units the order is indeterminate, so in practice the link order decides. When the registrar in `png_plugin.cpp` runs first, it calls `emplace` on a `std::map` whose constructor has not run yet: undefined behaviour, which crashed with exit status 139 on Apple clang 21 once `png_plugin.cpp` was listed before `registry.cpp`. The standard fix is **construct on first use**: replace the global with a function that returns a reference to a function-local static, so whoever needs the registry builds it. Where the value can be computed at compile time, C++20's `constinit` makes the compiler reject any dynamic initialization, so no order exists to get wrong.
code
console · 4 lines$ clang++ -std=c++20 registry.cpp png_plugin.cpp main.cpp -o good && ./good
plugins registered: 1
$ clang++ -std=c++20 png_plugin.cpp registry.cpp main.cpp -o bad && ./bad; echo "exit status $?"
exit status 139go deeper
Know that globals in different source files have no guaranteed initialization order, and that one global must not depend on another file's global at startup.
Explain zero, constant and dynamic initialization, and show construct-on-first-use as the standard fix with its C++11 thread-safety guarantee.
Diagnose a link-order-dependent crash before main, explain why it is undefined behaviour rather than a toolchain bug, and choose between construct-on-first-use, constinit and explicit initialization.
Turn the fix into a rule: which globals may need dynamic initialization at all, which tooling catches new ones, and how plugin registration stays automatic without hidden order.
## Static and dynamic initialization Every variable with static storage duration goes through up to two phases: - **Static initialization**: if the variable is *constant-initialized* (its initializer is a constant expression), that happens first; otherwise it is **zero-initialized**. All static initialization strongly happens before any dynamic initialization. - **Dynamic initialization**: everything else, such as running a non-`constexpr` constructor or calling an ordinary function. A `std::map` global built by its constructor at startup is in this phase. Between the two phases a dynamically initialized object exists only as zero bytes. Reading it then is not reading an empty map; it is using an object whose lifetime has not started. ## What the standard orders, and what it does not | Variables | Order of dynamic initialization | |---|---| | two ordinary globals in the **same** translation unit | definition order | | two ordinary globals in **different** translation units | indeterminately sequenced; with threads started first, even the initializing thread is unspecified | | an `inline` variable (C++17) | partially ordered: initialized before a later variable when it precedes every definition of that variable in the same translation unit | | a variable template specialization or a static member of a class template | unordered | The standard also lets an implementation defer a global's dynamic initialization until first use of something in its translation unit; whether it does is implementation-defined. Mainstream toolchains run them before `main`, in an order set by the object files and the linker, which is why the bug appears and disappears when a build file is reordered. ## The plugin host failure The scenario has three translation units: `registry.cpp` defines `std::map<std::string, Factory> g_registry;`, `png_plugin.cpp` defines `static bool png_registered = register_plugin("png", make_png);`, and `main.cpp` lists the registry's contents. On Apple clang 21, linking `registry.cpp` first printed one registered plugin; linking `png_plugin.cpp` first crashed with exit status 139 before `main`, and AddressSanitizer reported a SEGV inside the map's insert called from the registrar's initializer. That crash is one observed outcome of **undefined behaviour**, not a guarantee: another build might lose the entry silently when the map's constructor later resets it. ## Fixes, from most to least common 1. **Construct on first use.** Replace the global with `std::map<std::string, Factory>& registry() { static std::map<std::string, Factory> instance; return instance; }`. The first caller, whichever translation unit it lives in, builds the map, and since C++11 that is thread-safe. Both link orders then printed one plugin. 2. **Constant initialization.** If a global can be built at compile time, declare it `constinit` (C++20) or `constexpr`. `constinit` makes the program **ill-formed** if the variable would need dynamic initialization; Clang reports `variable does not have a constant initializer` with the note `required by 'constinit' specifier here`. It fits fixed tables, counters and `std::string_view` names, not a map filled at startup. 3. **Explicit initialization.** Have `main` call `init_plugins()` in a known order instead of relying on registrar side effects. This trades automatic registration for an order you can read. 4. **A reference-counted initializer object** (the "nifty counter" or Schwarz counter): every translation unit that includes the header gets a small static object whose constructor builds the shared object on first count. It works, but it is intricate and rarely worth it over the first fix. ## Finding it before production does - AddressSanitizer has an optional **initialization-order checker**, enabled with `ASAN_OPTIONS=check_initialization_order=1`; Clang's documentation notes it is not supported on macOS. - Clang's `-Wglobal-constructors` warns on declarations that need a global constructor or a global destructor, which makes such globals visible in review. - Shuffling the order of object files in a CI build turns a lucky order into a failing one. ## The point to make The crash is not a linker bug: the program relied on an order the standard never promised. Strong answers name the rule, show why link order masks it, and pick construct-on-first-use or `constinit` depending on whether the value is known at compile time.
- Why does constinit not fix this registry, when it fixes other globals?`constinit` requires constant initialization and makes the program ill-formed otherwise; it does not make the variable const. A registry that plugins fill at startup through `emplace` is built and mutated by runtime code, so the inserts still happen during dynamic initialization in some order. `constinit` helps the objects the registrars depend on, such as a fixed capacity or a `std::string_view` name, and construct-on-first-use handles the map itself.
- Within one translation unit, can a global safely use another global defined above it?Yes, for ordinary non-template globals: dynamic initialization in one translation unit follows definition order, so a variable defined earlier is initialized first. The reverse is not safe. Using a variable defined later in the same file may see only its zero-initialized value. Template static members and variable template specializations are unordered even inside one file.
- Is the function-local static fix free of ordering problems at program exit?Not entirely. Startup becomes safe, but statics are destroyed in reverse order of construction, so if some global was built before the first call to `registry()` and uses the registry in its destructor, it runs after the registry is gone. Calling `registry()` from that global's constructor, or deliberately never destroying the registry, closes that gap.
- Globals are initialized in the order their source files appear in the build file, as the standard requires.
- Initialization order between globals in the same source file is unspecified too.
- Declaring the registry const would make it initialize before the registrars.
- constinit works for any type, including a map that plugins fill at startup.
- The crash is a linker bug, because the program is correct C++.
Assumes C++20 or later for constinit; the cross-file ordering rule and construct on first use apply to every C++ standard.