When attempting to compile a C program with multiple header files, it's possible to encounter the error "multiple definition of [symbol]." This error occurs when the same symbol (such as a function or variable) is defined more than once in the code.
Consider the following example:
// complex.h #ifndef COMPLEX_H #define 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; }; #endif // COMPLEX_H // complex.cpp #include "complex.h" Complex::Complex(float Real, float Imaginary) { m_Real = Real; m_Imaginary = Imaginary; }
// operator.cpp #include "complex.h" std::ostream& operator<<(std::ostream& o, const Complex& Cplx) { return o << Cplx.m_Real << " i" << Cplx.m_Imaginary; }
// main.cpp #include "complex.h" #include <iostream> int main() { Complex Foo(3.4, 4.5); std::cout << Foo << "\n"; return 0; }
Compiling this code will result in the aforementioned error. The issue arises from the definition of the operator<< function in operator.cpp. While the header file includes a declaration of the function, the definition in operator.cpp is not inlined. Consequently, the compiler generates two separate definitions of the function, causing the multiple definition error.
Unlike public member functions like real(), which are implicitly inlined, non-member functions like operator<< need to be explicitly marked as inline to allow for multiple definitions.
To resolve this error, one can either:
// complex.h ... inline std::ostream& operator<<(std::ostream& o, const Complex& Cplx) { return o << Cplx.m_Real << " i" << Cplx.m_Imaginary; } ...
// complex.cpp ... std::ostream& operator<<(std::ostream& o, const Complex& Cplx) { return o << Cplx.m_Real << " i" << Cplx.m_Imaginary; } ...
By either inlining the function or placing its definition in the implementation file, the multiple definition error can be avoided, ensuring that the program compiles successfully.
The above is the detailed content of Why Does Defining a Function in a Header File Cause a \'Multiple Definition\' Error in C ?. For more information, please follow other related articles on the PHP Chinese website!