How do I resolve ODR (One Definition Rule) violations in C++?

In C++, the One Definition Rule (ODR) states that a variable, function, class, or template must be defined exactly once in a program. Violating this rule can lead to undefined behavior and linker errors. To resolve ODR violations, follow these strategies:

  • Keep definitions in a single translation unit to avoid multiple instances.
  • Use `inline` for functions defined in header files.
  • Utilize `extern` declarations for variables that need to be shared across translation units.
  • Leverage header guards to prevent multiple inclusions of the same header file.

Here's an example illustrating these concepts:

// foo.h #ifndef FOO_H #define FOO_H class Foo { public: void doSomething(); }; #endif // FOO_H // foo.cpp #include "foo.h" #include void Foo::doSomething() { std::cout << "Doing something!" << std::endl; } // main.cpp #include "foo.h" int main() { Foo foo; foo.doSomething(); return 0; }

ODR One Definition Rule C++ linker errors header guards