Note that there are some explanatory texts on larger screens.

plurals
  1. POSplitting templated C++ classes into .hpp/.cpp files--is it possible?
    primarykey
    data
    text
    <p>I am getting errors trying to compile a C++ template class which is split between a <code>.hpp</code> and <code>.cpp</code> file:</p> <pre><code>$ g++ -c -o main.o main.cpp $ g++ -c -o stack.o stack.cpp $ g++ -o main main.o stack.o main.o: In function `main': main.cpp:(.text+0xe): undefined reference to 'stack&lt;int&gt;::stack()' main.cpp:(.text+0x1c): undefined reference to 'stack&lt;int&gt;::~stack()' collect2: ld returned 1 exit status make: *** [program] Error 1 </code></pre> <p>Here is my code:</p> <p><strong>stack.hpp</strong>:</p> <pre><code>#ifndef _STACK_HPP #define _STACK_HPP template &lt;typename Type&gt; class stack { public: stack(); ~stack(); }; #endif </code></pre> <p><strong>stack.cpp</strong>:</p> <pre><code>#include &lt;iostream&gt; #include "stack.hpp" template &lt;typename Type&gt; stack&lt;Type&gt;::stack() { std::cerr &lt;&lt; "Hello, stack " &lt;&lt; this &lt;&lt; "!" &lt;&lt; std::endl; } template &lt;typename Type&gt; stack&lt;Type&gt;::~stack() { std::cerr &lt;&lt; "Goodbye, stack " &lt;&lt; this &lt;&lt; "." &lt;&lt; std::endl; } </code></pre> <p><strong>main.cpp</strong>:</p> <pre><code>#include "stack.hpp" int main() { stack&lt;int&gt; s; return 0; } </code></pre> <p><code>ld</code> is of course correct: the symbols aren't in <code>stack.o</code>.</p> <p>The answer to <a href="https://stackoverflow.com/questions/687448">this question</a> does not help, as I'm already doing as it says.<br> <a href="https://stackoverflow.com/questions/1111440/undefined-reference-error-for-template-method">This one</a> might help, but I don't want to move every single method into the <code>.hpp</code> file&mdash;I shouldn't have to, should I?</p> <p>Is the only reasonable solution to move everything in the <code>.cpp</code> file to the <code>.hpp</code> file, and simply include everything, rather than link in as a standalone object file? That seems <strong>awfully</strong> ugly! In that case, I might as well revert to my previous state and rename <code>stack.cpp</code> to <code>stack.hpp</code> and be done with it.</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