This rule is part of MISRA C++:2023.
Usage of this content is governed by Sonar’s terms and conditions. Redistribution is
prohibited.
Rule 6.0.3 - The only declarations [2] in the global namespace should be main, namespace declarations and extern
"C" declarations
Category: Advisory
Analysis: Decidable,Single Translation Unit
Amplification
This rule also prohibits use of using directives and inline namespaces in the global namespace.
It does not apply to namespace aliases, static_assert or to names that are declared within the C++ Standard.
Rationale
Declaring names into appropriate namespaces reduces the names found during lookup, helping to ensure that the names found meet developer
expectations.
Adherence with this rule is particularly important within header files [1], as it reduces the chance that the order of their inclusion
will affect program behaviour.
Notes:
- Using directives and inline namespaces do not actually add names to the global namespace, but they do make them appear as if
they are in it.
- Names declared within an anonymous namespace appear in the global namespace. However, their use is permitted as they do not
have external linkage.
Example
void f1( int32_t ); // Non-compliant
int32_t x1; // Non-compliant
namespace // Compliant
{
void f2( int32_t ); // Rule does not apply
int32_t x2; // Rule does not apply
}
namespace MY_API // Compliant
{
void b2( int32_t ); // Rule does not apply
int32_t x2; // Rule does not apply
}
using namespace MY_API; // Non-compliant
using MY_API::b2; // Non-compliant
namespace MY = MY_API; // Compliant
int main() // Compliant
{
extern void f3(); // Non-compliant
}
Glossary
[1] Header file
A header file is considered to be any file that is included during preprocessing (for example via the #include directive),
regardless of its name or suffix.
[2] Declaration
A declaration introduces the name of an entity into a translation unit (see [basic.def]/1).
An entity may be declared several times. The first declaration of an entity in a translation unit is
called an introduction [3]. All subsequent declarations are called redeclarations [4].
A definition [5] is a declaration, as described in [basic.def]/2.
[3] Introduction
See declaration [2].
[4] Redeclaration
See declaration [2].
[5] Definition
See declaration [2].
Copyright The MISRA Consortium Limited © 2023