C & C++

C & C++

Made by DeepSource

Definition in header file could result in ODR violation CXX-W2037

Bug risk
Minor

The One-Definition Rule (ODR) recommends maintaining only a single definition of an entity (variable or function). When an entity is defined in a header file rather than in a source file, there is a chance that the ODR rule might get violated when such a header is included in multiple source files.

To avoid such redefinitions, it is recommended that you only declare the entity in the header file (and only do so when the entity is used in the header file). Move the definition of such an entity to a source file.

By doing so, you ensure that there is only one definition of the entity across all source files. This helps prevent issues that can arise when working with multiple definitions of the same entity.

Bad practice

// Content of some.h file
int pi = 3.14;

namespace {
  int ncores = 8;
}

std::string DEBUG_LEVEL{"warn"};

std::string& getDebugLevel(void) {
  return DEBUG_LEVEL;
}

template<typename T>
T sum(T a, T b) {
  return a + b;
}
template <>
int sum(int a, int b) {
 return a + b;
}

Recommended

// Content of some.h file
int pi;

namespace {
  int ncores;
}

std::string DEBUG_LEVEL;

std::string& getDebugLevel(void);

template<typename T>
T sum(T a, T b) {
  return a + b;
}

References