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.5.2 - Internal linkage should be specified appropriately
Category: Advisory
Analysis: Decidable,Single Translation Unit
Amplification
Internal linkage for an entity is specified appropriately when:
- It is declared within an anonymous namespace; and
- None of its declarations [1] use the
extern keyword; and
- It is not declared
static.
This rule does not apply to variables declared constexpr or const.
Rationale
Whilst the static keyword can be used to give an entity internal linkage, it also has other uses, which may lead to
confusion. An entity is unambiguously given internal linkage when it is declared in an anonymous namespace, with the added advantage
that this declarative form can be consistently applied to all types of entity.
An entity in an anonymous namespace can be declared extern, but this does not have an impact on its linkage.
Example
static void f1(); // Non-compliant
namespace
{
void f2(); // Compliant
int32_t notExtern1; // Compliant
extern int32_t notExtern2; // Non-compliant
}
Glossary
[1] 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 [2]. All subsequent declarations are called redeclarations [3].
A definition [4] is a declaration, as described in [basic.def]/2.
[2] Introduction
See declaration [1].
[3] Redeclaration
See declaration [1].
[4] Definition
See declaration [1].
Copyright The MISRA Consortium Limited © 2023