Edit

Share via


Warning C26427

Global initializer accesses extern object 'symbol' (i.22)

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 guideline is applicable when initializers refer to another object that's considered to be extern.

Remarks

An object is deemed extern if it conforms to the following rules:

  • it's a global variable marked with extern specifier or it's a static member of a class;
  • it's not in an anonymous namespace;
  • it's not marked as const;
  • Static class members are considered global, so their initializers are also checked.

Code analysis name: NO_GLOBAL_INIT_EXTERNS

Example

External version check:

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

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

External version check made more reliable:

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

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