GeneralPurpose-StaticInitializationOrderFiascoΒΆ

Initialization of global objects should not depend on other translation units

Required inputs: IR

Static object initialization should not depend on other translation units. The order of initialization of global objects across translation units is undefined, so code that depends on this order causes unpredictable behavior. Keep initialization of global objects independent or use lazy initialization patterns.
Bad code (dependent initialization):
// file1.cpp
extern int global_value;   // from file2.cpp
int initialized = global_value * 10;  // ERROR: depends on file2 initialization order

// file2.cpp
int get_global_value() { return 42; }
int global_value = get_global_value();  // ERROR: may be initialized after file1.cpp uses it
Good code (independent initialization):
// file1.cpp
int initialized = 100;  // OK: no external dependencies

// file2.cpp
int global_value = 42;  // OK: independent
Good code (lazy initialization):
// header.h
int& get_global_value();

// file.cpp
int& get_global_value() {
    static int value = 42;  // OK: initialized on first call
    return value;
}

// usage
int initialized = get_global_value() * 10;  // OK: guaranteed proper order

Possible Messages

Key

Text

Severity

Disabled

extern_dependency

Initialization of static object depends on other translation unit

None

False

Options