One-definition rule (ODR) states that a function, variable, or type can have only one definition across the entire program, though declarations can be multiple. Violating ODR causes linker errors or undefined behavior. Templates, inline functions, and static variables in different translation units are exceptions.
Apply inline to function definitions in headers; use static or anonymous namespaces for internal linkage; understand ODR to avoid linker errors.
This example shows ODR violations and how to safely define things in headers.
// compile: g++ -o odr odr.cpp utils.cpp // run: ./odr // description: one-definition rule and safe header definitions #include <iostream> // Safe in header: inline function (single definition across translation units) inline void greet() { std::cout << "Hello\n"; } // Safe in header: template (instantiated per translation unit) template <typename T> void process(T value) { std::cout << "Processing\n"; } // Safe in header: static variable (separate per translation unit) static int counter = 0; // Unsafe in header (if included in multiple .cpp files): // void unsafe() { } // would violate ODR int main() { greet(); process(42); return 0; }