This is a draft version of a MISRA C++ 202x rule proposed for public review.
MISRA Rule 6.7.2
Category: Required
Analysis Type: Decidable,Single Translation Unit
Amplification
Global variables are:
- Variables defined in namespace scope; and
- Class static data members.
This rule does not apply to global variables that are:
-
constexpr
; or
-
const
and that are initialized through static initialization.
Rationale
Global variables can be accessed and modified from:
- Anywhere within the translation unit, if they have internal linkage; or
- Anywhere within the program, if they have external linkage.
This can lead to uncontrollable interactions between functions, with the risk of undefined behaviour occurring due to data races in
concurrent programs.
Additionally, certain aspects of the order of initialization of global variables are unspecified. This can lead to unpredictable results
for global variables that are initialized at run-time (dynamic initialization).
Example
int32_t foo();
int32_t i1 { foo() }; // Non-compliant
const int32_t i2 { i1 }; // Non-compliant - dynamic initialization
namespace
{
int32_t i3 { 0 }; // Non-compliant
constexpr int32_t bar()
{
return 42;
}
constexpr int32_t i4 { bar() }; // Rule does not apply - constexpr
const int32_t SIZE { 100 }; // Rule does not apply
} // - const without dynamic initialization
struct ComplexInit
{
ComplexInit();
};
const ComplexInit c1 {}; // Non-compliant - dynamic initialization
class StaticMember
{
int32_t x; // Rule does not apply
static int32_t numInstances;
};
int32_t StaticMember::numInstances = 0; // Non-compliant
constexpr auto add = // Rule does not apply - add is const
[]( auto x, auto y ) { return x + y; };
Copyright The MISRA Consortium Limited © 2023