title: Template Function declared in header, defined in seperate .cpp file causing undefined reference error
body: <p>So I've learnt that it's best to first declared function in header file, than define it in a seperate <code>.cpp</code> file as function definition within headers aren't recommended. And I did so, with normal function and it worked. but when I try to do the same thing with template functions, it gave back error like</p>
  <pre><code>/usr/sbin/ld: /tmp/cc196bnS.o: in function `main':
  test.cpp:(.text+0x11): undefined reference to `double d::numerical::test&lt;double&gt;(double)'
  collect2: error: ld returned 1 exit status
  </code></pre>
  <p>Following will be a minimal working example where in header file I've define a normal function <code>d::numerical::test2(double)</code> and a template function <code>template&lt;typename T&gt; d::numerical::test(T)</code>. Then <code>cout</code> their returning value individually in <code>test.cpp</code>. Compiled with <code>g++ integration.cpp test.cpp</code>, the one calling normal function <code>test2</code> compiled and ran successfully, yet if I change it to <code>test</code> it throws the error as shown above.</p>
  <p>Notice I've also added a <code>const</code> and a class in the header file, and those can also be accessed to ensure that the file actually get included properly.</p>
  <p>I've read online (<a href="https://www.daniweb.com/programming/software-development/threads/439296/template-function-in-header-file" rel="nofollow noreferrer">here</a>) that it seems template functions' definition must also be in header file? But doesn't that goes against the rule that don't define function in header? What is the proper solution for these cases?</p>
  <hr />
  <h2 id="mwe-kqhe">MWE</h2>
  <p><code>test.cpp</code></p>
  <pre><code>#include&lt;bits/stdc++.h&gt;
  #include&quot;./integration.hpp&quot;
  
  using namespace std;
  
  int main() {
      cout &lt;&lt; d::numerical::test(1.) &lt;&lt; std::endl;
      return 0;
  }
  </code></pre>
  <p><code>integration.hpp</code></p>
  <pre><code>#ifndef __FUNC_NUM_INTE__
  #define __FUNC_NUM_INTE__
  namespace d { namespace numerical {
      const double EPS=1e-24;
      double test2(double);
      template&lt;typename T&gt; double test(T);
      template&lt;typename T&gt;
          class dp {
              T odd, even;
          };
  }}
  #endif
  </code></pre>
  <p><code>integration.cpp</code></p>
  <pre><code>#include&quot;integration.hpp&quot;
  
  double d::numerical::test2(double x) {
      return x;
  }
  
  template&lt;typename T&gt;
  double d::numerical::test(T x) {
      return x;
  }
  </code></pre>