How do I resolve ODR violations during linking?

Resolving ODR Violations During Linking in C++

One Definition Rule (ODR) violations occur in C++ when there are multiple definitions of the same entity (like functions or variables) across different translation units. These can lead to linkage errors. To address ODR violations, follow these strategies:

  • Use the static keyword for internal linkage to limit visibility.
  • Utilize header guards or #pragma once to prevent multiple inclusions.
  • Ensure that each entity is defined only once in a single translation unit, preferably in a .cpp file rather than a header file.
  • Use inline functions for template functions defined in headers to avoid ODR issues.

Example


        // Example to avoid ODR violations
        // my_functions.h
        #ifndef MY_FUNCTIONS_H
        #define MY_FUNCTIONS_H

        int add(int a, int b); // Declaration

        #endif // MY_FUNCTIONS_H

        // my_functions.cpp
        #include "my_functions.h"

        int add(int a, int b) { // Definition
            return a + b;
        }

        // main.cpp
        #include "my_functions.h"

        int main() {
            int sum = add(5, 10);
            return 0;
        }
    

ODR violations C++ linking errors One Definition Rule