What is the One Definition Rule (ODR), and what happens if it is violated?
Last updated
The One Definition Rule (ODR) requires exactly one definition of each non-inline function and variable in the program, though it may be declared many times.
Classes, templates, enums, and
inlinefunctions/variables may be defined in multiple translation units (e.g. via headers) only if all copies are identical.Duplicate definitions cause multiple-definition link errors. Inconsistent definitions are undefined behavior with no diagnostic, often causing silent crashes or corruption.
- https://medium.com/@kunal-mod/c-best-practices-understanding-the-need-for-splitting-class-declaration-and-definitions-into-389d523695b9
- https://www.geeksforgeeks.org/dsa/why-can-templates-only-be-implemented-in-the-header-file/
- https://dev.to/christiandaley/virtual-function-templates-with-stateful-metapogramming-in-c-20-33l2
- https://github.com/MicrosoftDocs/cpp-docs/blob/main/docs/cpp/program-and-linkage-cpp.md