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.2.4 - A header file [1] shall not contain definitions of functions or objects that are non-inline and have external linkage
[basic.def.odr]
Category: Required
Analysis: Decidable, Single Translation Unit
Amplification
This rule prohibits the definition within a header file [1] of non-inline:
- Namespace-scope variables; and
- Namespace-scope functions; and
- Static and non-static member functions; and
- Non-
const, static data members.
This rule does not apply to entities without linkage (scope local entities) or entities with internal linkage.
Rationale
Header files [1] should be used to declare C++ templates, types, functions, references and objects.
Defining a non-inline entity (function or object) with external linkage in a header file [1] causes a violation of the
one-definition rule when that header file [1] is included in multiple translation units, resulting in undefined
behaviour.
Whilst defining non-inline entities with internal linkage in header files [1] can cause needless duplication, it is not a
violation of this rule.
Entities defined explicitly or implicitly as inline, or without external linkage, can appear in header files [1] without
risking violation of the one-definition rule if all definitions across all translation units are consistent. The latter can be
guaranteed by using a single header file [1] to define such an entity (see M23_053: MISRA C++ 2023
Rule 6.2.3).
Example
// Header file a.h
void f1(); // Rule does not apply - not a definition
void f2() { } // Non-compliant
inline void f3() { } // Compliant
template< typename T >
void f4( T ) { } // Compliant - implicitly inline
int32_t a; // Non-compliant
constexpr auto ans { 42 }; // Compliant - no external linkage
struct X
{
int32_t a; // Compliant - no linkage
inline static const
int32_t b { 2 }; // Compliant - X::b has external linkage but is inline
};
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.
Copyright The MISRA Consortium Limited © 2023