MISRA C++:2023 Rule 6.7.2
Description
Rule Definition
Global variables shall not be used.
Rationale
A global variable is:
A variable declared in
namespace
scope, including the global namespace.A
static
data member in a class.
Depending on the linkage of such a variable, it can be read or written from anywhere in a source file or a program. Such widespread access to nonlocal objects can lead to various problems:
Because many functions and entities can read or write these global variables, their interactions become unpredictable.
Because multiple functions can access these global variables simultaneously, concurrent programs can face the risk of undefined behavior caused by a data race.
Because the order of initialization of these global variables is not completely specified by the C++ standard, the value of such a variable can be unpredictable if the variable is initialized dynamically.
Avoid using global variables, except for these variables that do not violate the rule:
constexpr
variablesconst
variables that are initialized through static initializationVariables holding a lambda without lambda capture
Polyspace Implementation
Polyspace® reports a violation of this rule if you declare any of these objects:
A global or namespace-scope variable that is neither
const
norconstexpr
A dynamically initialized
const
global or namespace-scope variableA
static
class member
Troubleshooting
If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.
Examples
Check Information
Group: Basic Concepts |
Category: Required |
Version History
Introduced in R2024b