multiple definition in header file

Posted by Jérôme on Stack Overflow See other posts from Stack Overflow or by Jérôme
Published on 2010-04-28T07:39:25Z Indexed on 2010/04/28 7:43 UTC
Read the original article Hit count: 261

Filed under:
|

Here is a small code-example from which I'd like to ask a question :

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 this code, I get the following error :

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

I've found that making this fonction inline solves the problem, but I don't understand why. Why does the compiler complain about multiple definition ? My header file is guarded (with #define COMPLEX_H).

And, if complaining about the operator<< fonction, why not complain about the public real() fonction, which is defined in the header as well ?

And is there another solution as using the inline keyword ?

© Stack Overflow or respective owner

Related posts about c++

Related posts about header-files