c++ - multiple definition in header file -


given code sample:

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; };  std::ostream& operator<<(std::ostream& o, const complex& cplx) {    return o << cplx.m_real << " i" << cplx.m_imaginary; } #endif // complex_h 

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 code, following error:

multiple definition of operator<<(std::ostream&, complex const&) 

i've found making function inline solves problem, don't understand why. why compiler complain multiple definition? header file guarded (with #define complex_h).

and, if complaining operator<< function, why not complain public real() function, defined in header well?

and there solution besides using inline keyword?

the problem following piece of code definition, not declaration:

std::ostream& operator<<(std::ostream& o, const complex& cplx) {    return o << cplx.m_real << " i" << cplx.m_imaginary; } 

you can either mark function above , make "inline" multiple translation units may define it:

inline std::ostream& operator<<(std::ostream& o, const complex& cplx) {    return o << cplx.m_real << " i" << cplx.m_imaginary; } 

or can move original definition of function "complex.cpp" source file.

the compiler not complain "real()" because implicitly inlined (any member function body given in class declaration interpreted if had been declared "inline"). preprocessor guards prevent header being included more once single translation unit ("*.cpp" source file"). however, both translation units see same header file. basically, compiler compiles "main.cpp" "main.o" (including definitions given in headers included "main.cpp"), , compiler separately compiles "complex.cpp" "complex.o" (including definitions given in headers included "complex.cpp"). linker merges "main.o" , "complex.o" single binary file; @ point linker finds 2 definitions function of same name. @ point linker attempts resolve external references (e.g. "main.o" refers "complex::complex" not have definition function... linker locates definition "complex.o", , resolves reference).


Comments

Popular posts from this blog

Delphi Wmi Query on a Remote Machine -