Consider the following 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& o, const Complex& Cplx); float m_Real; float m_Imaginary; }; std::ostream& operator<<(std::ostream& o, const Complex& Cplx) { return o << Cplx.m_Real << " i" << Cplx.m_Imaginary; } // 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 reports an error:
multiple definition of operator<<(std::ostream&, Complex const&)
The reason for this error is that the definition of the operator<< function in complex.h is not a declaration but an actual definition. This means that when both complex.cpp and main.cpp include the header file, the compiler attempts to define the function twice. This leads to the multiple definition error.
The compiler does not complain about the public member function real() because it is implicitly inlined. This means that the compiler generates the code for real() in every translation unit that uses it.
There are two main solutions to this issue:
Make operator<< an Inline Function:
By marking the operator<< function as inline, it can be defined in multiple translation units.
inline std::ostream& operator<<(std::ostream& o, const Complex& Cplx) { return o << Cplx.m_Real << " i" << Cplx.m_Imaginary; }
Move operator<< Definition to complex.cpp:
Alternatively, you can define the operator<< function in the complex.cpp source file, which ensures that it is defined only once.
Besides using the inline keyword or moving the definition to a source file, there is another possible solution:
Use Header Guards in Function Definitions:
You can add header guards around the function definition to prevent it from being defined more than once.
#ifndef OPERATOR_LT_LT_DEFINED #define OPERATOR_LT_LT_DEFINED std::ostream& operator<<(std::ostream& o, const Complex& Cplx) { return o << Cplx.m_Real << " i" << Cplx.m_Imaginary; } #endif // OPERATOR_LT_LT_DEFINED
The above is the detailed content of Why does including a header file with a function definition in multiple source files lead to a \'multiple definition\' error?. For more information, please follow other related articles on the PHP Chinese website!