Note that there are some explanatory texts on larger screens.

plurals
  1. POundefined reference when using templates
    text
    copied!<p>Keep on getting undefined reference which other answers say should be linking issue. Am I not compiling this correctly? Or is there something wrong in the code? I've tried throwing main into stack.cpp and it compiles and runs fine, but I'm not sure what else needs to be done to link main.o and stack.o and why it suddenly is throwing a fit now that I've added this one file.</p> <p>stack.h:</p> <pre><code>#ifndef STACK_INCLUDED #define STACK_INCLUDED #include &lt;cstddef&gt; template&lt;typename T&gt; struct Node { Node(T _data, Node&lt;T&gt; * _next) : data(_data), next(_next) {} T data; Node&lt;T&gt; *next; }; template&lt;class T&gt; class Stack { private: Node&lt;T&gt; *first; public: Stack(void); bool isEmpty(void); void push(T n); T pop(void); }; #endif </code></pre> <p>stack.cpp:</p> <pre><code>#include "stack.h" template&lt;class T&gt; Stack&lt;T&gt;::Stack(void) { first = NULL; } template&lt;class T&gt; bool Stack&lt;T&gt;::isEmpty(void) { return first == NULL; } template&lt;class T&gt; void Stack&lt;T&gt;::push(T n) { Node&lt;T&gt; *oldfirst = first; Node&lt;T&gt; *newfirst = new Node&lt;T&gt;(n, oldfirst); first = newfirst; first-&gt;next = oldfirst; } template&lt;class T&gt; T Stack&lt;T&gt;::pop(void) { T data = first-&gt;data; first = first-&gt;next; return data; } </code></pre> <p>main.cpp:</p> <pre><code>#include &lt;iostream&gt; #include "stack.h" using namespace std; int main(void) { Stack&lt;int&gt; s; if (!s.isEmpty()) { cout &lt;&lt; "not empty" &lt;&lt; endl; } return 0; } </code></pre> <p>Try to compile:</p> <pre><code>$ g++ stack.cpp -c $ g++ main.cpp -c $ g++ main.o stack.o main.o: In function `main': main.cpp:(.text+0x10): undefined reference to `Stack&lt;int&gt;::Stack()' main.cpp:(.text+0x1c): undefined reference to `Stack&lt;int&gt;::isEmpty()' collect2: ld returned 1 exit status </code></pre>
 

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