Home >Backend Development >C++ >Why Do I Get \'Multiple Definition\' Errors in Header Files, and How Can I Fix Them?
Multiple Definition Errors in Header Files: Why and How to Resolve Them
Compilers encounter "multiple definition" errors when they are presented with multiple definitions of a symbol in the same program. This can occur when multiple source files include the same header file, each of which defines the same symbol.
Let's examine the provided code sample:
// complex.h #include <iostream> class Complex { public: Complex(float Real, float Imaginary); float real() const { return m_Real; }; private: friend std::ostream& operator<< (std::ostream&, const Complex&); float m_Real; float m_Imaginary; }; std::ostream& operator<< (std::ostream& o, const Complex& Cplx) { return o << Cplx.m_Real << " i" << Cplx.m_Imaginary; }
The operator<< function is defined in the .h file, making it a candidate for multiple definition since multiple source files will include it.
// complex.cpp #include "complex.h" Complex::Complex(float Real, float Imaginary) { m_Real = Real; m_Imaginary = Imaginary; }
// main.cpp #include "complex.h" #include <iostream> int main() { Complex Foo(3.4, 4.5); std::cout << Foo << "\n"; return 0; }
When compiling this code, the compiler encounters a "multiple definition" error for the operator<< function.
Why Not for real()?
The real() member function is implicitly inlined, meaning the compiler treats it as if it were declared inline even though it is not explicitly specified in the .h file.
Resolutions
To resolve the multiple definition issue for the operator<< function, there are two main alternatives:
Inline the Function:
Add the inline keyword to the function definition to instruct the compiler to inline it:
inline std::ostream& operator<< (std::ostream& o, const Complex& Cplx) { return o << Cplx.m_Real << " i" << Cplx.m_Imaginary; }
Move the Definition to the .cpp File:
Remove the function definition from the .h file and place it in the corresponding .cpp file:
// complex.cpp std::ostream& operator<< (std::ostream& o, const Complex& Cplx) { return o << Cplx.m_Real << " i" << Cplx.m_Imaginary; }
Other Solutions
Additional solutions include:
The above is the detailed content of Why Do I Get \'Multiple Definition\' Errors in Header Files, and How Can I Fix Them?. For more information, please follow other related articles on the PHP Chinese website!