title: C++ Shared Library with Templates: Undefined symbols error
body: <p>I'm trying to link to a shared library with a template class, but it is giving me "undefined symbols" errors. I've condensed the problem to about 20 lines of code.</p>
  
  <p><strong>shared.h</strong></p>
  
  <pre><code>template &lt;class Type&gt; class myclass {
    Type x;
  public:
    myclass() { x=0; }
    void setx(Type y);
    Type  getx();
  };
  </code></pre>
  
  <p><strong>shared.cpp</strong></p>
  
  <pre><code>#include "shared.h"
  template &lt;class Type&gt; void myclass&lt;Type&gt;::setx(Type y) { x = y; }
  template &lt;class Type&gt; Type myclass&lt;Type&gt;::getx() { return x; }
  </code></pre>
  
  <p><strong>main.cpp</strong></p>
  
  <pre><code>#include &lt;iostream&gt;
  #include "shared.h"
  using namespace std;
  
  int main(int argc, char *argv[]) {
     myclass&lt;int&gt; m;
     cout &lt;&lt; m.getx() &lt;&lt; endl;
     m.setx(10);
     cout &lt;&lt; m.getx() &lt;&lt; endl;
     return 0;
  }
  </code></pre>
  
  <p>This is how I compile the library:</p>
  
  <pre><code>g++ -fPIC -c shared.cpp -o shared.o
  g++ -dynamiclib -Wl,-dylib_install_name -Wl,libshared.dylib -o libshared.dylib shared.o
  </code></pre>
  
  <p>And the main program:</p>
  
  <pre><code>g++ -c main.cpp
  g++ -o main  main.o -L. -lshared
  </code></pre>
  
  <p>Only to get the following errors:</p>
  
  <pre><code>Undefined symbols:
  "myclass&lt;int&gt;::getx()", referenced from:
    _main in main.o
    _main in main.o
  "myclass&lt;int&gt;::setx(int)", referenced from:
    _main in main.o
  </code></pre>
  
  <p>If I remove the 'template' stuff in <code>shared.h/cpp</code>, and replace them with just 'int', everything works fine. Also, if I just copy&amp;paste the template class code right into <code>main.cpp</code>, and don't link to the shared library, everything works as well. </p>
  
  <p>How can I get a template class like this to work through a shared library?</p>
  
  <p>I'm using MacOS 10.5 with GCC 4.0.1.</p>