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.1 - The one-definition rule shall not be violated
[basic.def.odr] Undefined 6.6
Category: Required
Analysis: Decidable,System
Rationale
Violation of the one-definition rule (ODR [1]) results in undefined behaviour — for example, when an entity
has:
- No definition; or
- Multiple non-inline definitions in different translation units; or
- Multiple inline definitions in different translation units that are not the same; or
- Different initializer values.
Example
// File a.cpp
struct S1
{
int32_t i;
};
struct S2
{
int32_t i;
};
// File b.cpp
struct S1
{
int64_t i;
}; // Non-compliant - definitions of S1 are not the same
struct S2
{
int32_t i;
int32_t j;
}; // Non-compliant - definitions of S2 are not the same
The following example is non-compliant as File1.cpp and File2.cpp introduce different definitions of h, with
the call they contain to f resolving to different overloads in each definition.
// File1.h
void f( int32_t i );
// File2.h
void f( int64_t i );
// File3.h
inline void h( int64_t i )
{
f( i ); // Nested call
}
// File1.cpp
#include "File1.h"
#include "File3.h"
void f1()
{
h( 42 ); // Nested call in h is to int32_t overload of f
}
// File2.cpp
#include "File2.h"
#include "File3.h"
void f2()
{
h( 42 ); // Nested call in h is to int64_t overload of f
}
Glossary
[1] ODR
ODR is an abbreviation for the one-definition rule.
Copyright The MISRA Consortium Limited © 2023