C26427 NO_GLOBAL_INIT_EXTERNS

"Global initializer accesses extern object."

C++ Core Guidelines: I.22: Avoid complex initialization of global objects

Global objects may be initialized in an inconsistent or undefined order which means that interdependency between them is risky and should be avoided. This is specifically applicable when initializers refer to another object considered to be ‘extern’.

Remarks

  • An object is deemed extern if it conforms to the following rules:
    • it is a global variable marked with ‘extern’ specifier or it is a static member of a class;
    • it is not in an anonymous namespace;
    • it is not marked as ‘const’;
    • Static class members are considered global, so their initializers are also checked. ## Example external version check // api.cpp
int api_version = API_DEFAULT_VERSION; // Assume it can change at runtime, hence non-const.

// client.cpp
extern int api_version;
bool is_legacy_mode = api_version <= API_LEGACY_VERSION; // C26427, also stale value

Example

external version check – made more reliable

// api.cpp
int api_version = API_DEFAULT_VERSION; // Assume it can change at runtime, hence non-const.

// client.cpp
extern int api_version;
bool is_legacy_mode() noexcept
{
    return api_version <= API_LEGACY_VERSION;
}