Note that there are some explanatory texts on larger screens.

plurals
  1. POmultiple definition in header file
    primarykey
    data
    text
    <p>Given this code sample:</p> <p><strong>complex.h :</strong></p> <pre><code>#ifndef COMPLEX_H #define COMPLEX_H #include &lt;iostream&gt; class Complex { public: Complex(float Real, float Imaginary); float real() const { return m_Real; }; private: friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; o, const Complex&amp; Cplx); float m_Real; float m_Imaginary; }; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; o, const Complex&amp; Cplx) { return o &lt;&lt; Cplx.m_Real &lt;&lt; " i" &lt;&lt; Cplx.m_Imaginary; } #endif // COMPLEX_H </code></pre> <p><strong>complex.cpp :</strong></p> <pre><code>#include "complex.h" Complex::Complex(float Real, float Imaginary) { m_Real = Real; m_Imaginary = Imaginary; } </code></pre> <p><strong>main.cpp :</strong></p> <pre><code>#include "complex.h" #include &lt;iostream&gt; int main() { Complex Foo(3.4, 4.5); std::cout &lt;&lt; Foo &lt;&lt; "\n"; return 0; } </code></pre> <p>When compiling this code, I get the following error:</p> <pre><code>multiple definition of operator&lt;&lt;(std::ostream&amp;, Complex const&amp;) </code></pre> <p>I've found that making this function <code>inline</code> solves the problem, but I don't understand why. Why does the compiler complain about multiple definition? My header file is guarded (with <code>#define COMPLEX_H</code>).</p> <p>And, if complaining about the <code>operator&lt;&lt;</code> function, why not complain about the <code>public real()</code> function, which is defined in the header as well?</p> <p>And is there another solution besides using the <code>inline</code> keyword?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload