title: Understanding extern templates in c++
body: <p>I am trying to understand extern templates, but i can't get it to work. My goal is to compile some instanciations if <code>Foo&lt;&gt;</code> in a seperate compilation unit in order to save compilation time. In my code base, the template argument is a <code>enum class</code>, so in theory I am able to compile all instanciations in a compilation unit and link them with the rest of the project.</p>
  
  <p>Here is a little example I come up with:</p>
  
  <pre><code>//Foo.hpp
  #pragma once
  
  template &lt;class T&gt;
  struct Foo {
      Foo();
      ~Foo();
  };
  
  extern template struct Foo&lt;int&gt;;
  </code></pre>
  
  <hr>
  
  <pre><code>//Foo.cpp
  #include "Foo.hpp"
  
  template struct Foo&lt;int&gt;;
  </code></pre>
  
  <hr>
  
  <pre><code>//main.cpp
  #include &lt;iostream&gt;
  
  #include "Foo.hpp"
  
  int main(int argc, char **argv) {
     Foo&lt;int&gt; foo;
  
      return 0;
  }
  </code></pre>
  
  <p>To for compilation i used a makefile, that boils down to this:</p>
  
  <pre><code>g++ -c ../Foo.cpp ../main.cpp
  g++ Foo.o main.o 
  </code></pre>
  
  <p>The output I get with gcc 7.1.1 and basically the same with clang 4.0.1 is:</p>
  
  <pre><code>main.o: In function `main':
  main.cpp:(.text+0x27): undefined reference to `Foo&lt;int&gt;::Foo()'
  main.cpp:(.text+0x38): undefined reference to `Foo&lt;int&gt;::~Foo()'
  </code></pre>
  
  <p>My main question is, why is <code>Foo&lt;int&gt;::Foo()</code> and <code>Foo&lt;int&gt;::~Foo()</code>not compiled into <code>Foo.o</code>?</p>