Back to Blog
one definition rule (odr)
May 9, 2026
1 min read
c++
the one definition rule is as follows:
- in a file, a function, variable, type, or template in a given scope, must only have one definition
- in a program, a (non-inlined) function or (non-inlined) variable in a given scope must only have one definition
knowing the odr can save you loads of time when compiling (or linking) larger projects.
for example, the following example violates part 1 of the odr:
int main()
{
int x = 0;
int x = 0;
}
when the compiler reaches the second line, it will error out, complaining about a redefinition of x.
on the other hand, the following example violates part 2 of the odr:
// declarations.h
int f();
// a.cpp
int f()
{
return 1;
}
// b.cpp
int f()
{
return 1;
}
// main.cpp
#include "declarations.h"
int main()
{
f();
}
in this case, when compiled with g++ a.cpp b.cpp main.cpp, a.cpp will compile fine, b.cpp will compile fine, but there will be a linker error because of the multiple definitions of f().