当尝试编译具有多个头文件的 C 程序时,可能会遇到错误“多重定义 [符号” ]。”当同一符号(例如函数或变量)在代码中定义多次时,就会出现此错误。
请考虑以下示例:
// 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; }
编译此代码将导致上述错误。问题源于运算符
与 real() 等公共成员函数不同,real() 是隐式内联的,非成员函数如 operator
要解决此错误,可以:
// 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; } ...
通过内联函数或将其定义放在实现文件中,可以避免多重定义错误,确保程序编译成功。
以上是为什么在头文件中定义函数会导致 C 中的'多重定义”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!