The one-definition rule (ODR) is a rule in C++ which contains three parts:

  1. In a file, each function, variable, type or template in a given scope should only have one definition. Definitions occurring in different scopes or namespaces do not violate this rule. Violation of this gives compilation error.
  2. In a program, each function or variable in a given scope should only have one definition. This exists because a program can consists of multiple files. Violation of this gives linker error.
  3. Types, templates, inline functions, and inline variables can have duplicate definitions in different files. The definitions should be identical.

For example,

In a single file,

int a = 1;
int a = 2; // violation of ODR

In multiple files,

main.cpp

#include <iostream>
 
int add(int a, int b)
{
  return a + b;
}
 
int main()
{
  std::cout << add(1, 2);
  return 0;
}
 

add.cpp

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

If we compile the program using the command,

clang++ -ggdb -std=c++20 main.cpp add.cpp -o add

It will give linker error for duplicate definitions.

References

  1. https://www.learncpp.com/cpp-tutorial/forward-declarations/#ODR