Main Content

MISRA C++:2023 Rule 6.2.1

The one-definition rule shall not be violated

Since R2024b

Description

Rule Definition

The one-definition rule shall not be violated.

Rationale

Violations of the one definition rule (ODR) leads to undefined behavior. The ODR is violated when an entity in you code:

  • Does not have a definition.

  • Has multiple noninline definitions in different source files.

  • Has multiple different inline definitions in different source files.

  • Has different initializer values.

Polyspace Implementation

The rule checker reports violations when:

  • The same function or object has multiple definitions and the definitions differ by some token.

  • An inline function has different implementations in different source files.

The checker is not raised on unused code such as

  • Noninstantiated templates

  • Uncalled static or extern functions

  • Uncalled and undefined local functions

  • Unused types and variables

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

This example uses two files:

  • file1.cpp:

    typedef struct S //Noncompliant
    {
       int x;
       int y;
    }S; 
    void foo(S& s){
    //...
    } 
  • file2.cpp:

    typedef struct S 
    {
       int y;
       int x;
    }S ; 
    void bar(S& s){
    //...
    }

In this example, both file1.cpp and file2.cpp define the structure S. However, the definitions switch the order of the structure fields.

This example uses three header files and two source files:

Header filesSource Files

  • File1.h:

    void  foo(int32_t i);

  • File2.h:

    void  foo(int64_t i);

  • File3.h:

    inline void bar(int64_t i){
    foo(i);
    }

  • File1.cpp:

    #include<cstdint>
    #include "File1.h"
    #include "File3.h"
    void f1(){
    
    bar(23);
    }
    

  • File2.cpp:

    #include<cstdint>
    #include "File2.h"
    #include "File3.h"
    void f2(){
    
    bar(23);
    }
    

In File1.cpp, the inline function bar() includes a call to foo(int32_t i) but in File2.cpp, the function bar() includes a call to foo(int64_t i). The different definition of the same inline function in different translation units results in a violation of this rule.

Check Information

Group: Basic concepts
Category: Required

Version History

Introduced in R2024b