Multiple Definition Error: A Solution to Conflicting Definitions
In C , when defining functions or classes in headers and implementing them in source files, developers may encounter the error "multiple definition." This error arises when multiple translation units (source files) contain definitions for the same identifier.
Causes of Multiple Definition
The error "multiple definition" occurs when header files containing definitions are included in multiple translation units. This can happen when:
Understanding the Error
Consider the code sample provided:
// complex.h class Complex { public: friend std::ostream& operator<<(std::ostream&, const Complex&); }; // complex.cpp std::ostream& operator<<(std::ostream&, const Complex&);
In this example, the definition of the operator << is in complex.h instead of complex.cpp. This can lead to a multiple definition error because both main.cpp and complex.cpp will attempt to define the << operator for the Complex class.
Solutions to Multiple Definitions
The solutions for the multiple definition error are:
Using the inline keyword or moving the definition to the source file are the preferred solutions for avoiding the multiple definition error.
Difference in Handling real() and <<
In the code sample, the real() function is declared in complex.h, but not defined. This is why the compiler does not report a multiple definition error for it. Member functions declared in class declarations are implicitly inlined, meaning their definitions are inserted into all translation units that include the header. This is not the case for the operator << function, which is defined in complex.h.
The above is the detailed content of Why Does My C Code Throw a 'Multiple Definition” Error?. For more information, please follow other related articles on the PHP Chinese website!