Main Content

MISRA C++:2023 Rule 6.2.4

A header file shall not contain definitions of functions or objects that are non-inline and have external linkage

Since R2024b

Description

Rule Definition

A header file shall not contain definitions of functions or objects that are non-inline and have external linkage.

Rationale

If a header file with variable or function definitions appears in multiple inclusion paths, the header file violates the One Definition Rule possibly leading to unpredictable behavior. For example, consider a header file myHeader.h that has a function definition. If this header is included in your analysis multiple time, the function violates the One Definition Rule. This can happen when you include myHeader.h and another header file which in-turn also includes myHeader.h.

Avoid definition of these non-inline entities in a header file:

  • Namespace-scope variables

  • namespace-scope function

  • Static and nonstatic member functions

  • Non-const static data member

Polyspace Implementation

The rule checker flags variable and function definitions in header files.

Polyspace® reports violation of this rule in header files. In a nonheader source file, violation of this rule is not reported.

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

expand all

In this example, Polyspace reports violations of this rule when variables and function definitions are placed in the header file header.hpp.

// header.hpp
#include <cstdint>
void F1();        // Compliant
extern void F2(); // Compliant
void F3()         // Noncompliant
{
}
static inline void F4()
{
} // Compliant
template <typename T>
void F5(T) // Compliant
{
}
std::int32_t a;                       // Noncompliant
extern std::int32_t b;                // Compliant
constexpr static std::int32_t c = 10; // Compliant
namespace ns
{
    constexpr static std::int32_t d = 100; // Compliant
    const static std::int32_t e = 50;      // Compliant
    static std::int32_t f;                 // Noncompliant
    static void F6() noexcept;             // Noncompliant
}

//source.cpp
#include "header.hpp"
void foo()
{
	//...
}

The flagged definitions can be moved to the source file to resolve the violations.

Check Information

Group: Basic Concepts
Category: Required

Version History

Introduced in R2024b