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.1 - A function or object with external linkage should be introduced in a header file [1]
[basic.scope.namespace]
Category: Advisory
Analysis: Decidable,Single Translation Unit
Amplification
This rule applies to functions and objects with namespace scope. The header file [1] containing the introduction [2]
should be included by every translation unit in which it is defined or used.
This rule does not apply to the function main.
Rationale
Placing the introductions [2] of functions and objects with external linkage in a header file [1] indicates that they are
intended to be accessed from multiple translation units. Requiring that this header file [1] is included by every translation
unit that defines or uses the function or object ensures that the declaration matches the definition.
If usage from multiple translation units is not required, then the visibility of the function or object should be reduced by declaring it
with internal linkage, for example, by declaring it within an unnamed namespace of an implementation file (see M23_055:
MISRA C++ 2023 Rule 6.5.2). This has the effect of increasing isolation and encapsulation, which is considered to be good practice.
Compliance with this rule helps to prevent the issues identified in M23_050: MISRA C++ 2023 Rule 6.2.2.
Example
// header.hpp
extern int32_t a1; // Compliant
extern void f3(); // Compliant
// file1.cpp
#include "header.hpp"
int32_t a1 = 0; // Redeclaration - rule does not apply
int32_t a2 = 0; // Non-compliant - no declaration in header
namespace
{
int32_t const a3 = 0; // Internal linkage - rule does not apply
void f1() // Internal linkage - rule does not apply
{
}
}
void f2() // Non-compliant - no declaration in header
{
}
void f3() // Redeclaration - rule does not apply
{
}
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] Introduction
See declaration [3].
[3] 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 [4].
A definition [5] is a declaration, as described in [basic.def]/2.
[4] Redeclaration
See declaration [3].
[5] Definition
See declaration [3].
Copyright The MISRA Consortium Limited © 2023