title: Function template in a namespace in a separate file compiles fine, but the linker cannot find it
body: <p>This problem is in defining and declaring a function template in a namespace that is defined in an external file from where the function is instantiated. Here's the smallest reproducible example I could come up with. 4 files follow:</p>
  
  <p>The function template declaration in a named namespace:</p>
  
  <pre><code>// bar.h
  #include &lt;algorithm&gt;
  
  namespace barspace {
  
    template &lt;typename Iter&gt;
      void DoSomething (Iter first, Iter last);
  
  }
  </code></pre>
  
  <p>The function template definition in a separate file:</p>
  
  <pre><code>// bar.cpp
  #include "bar.h"
  
  namespace barspace {
  
    template &lt;typename Iter&gt;
      void DoSomething (Iter first, Iter last) {
        typedef typename std::iterator_traits&lt;Iter&gt;::value_type val_t;
        std::sort (first, last);
      }
  
  } // namespace barspace
  </code></pre>
  
  <p>The header for the main program</p>
  
  <pre><code>// foo.h
  #include "bar.h"
  #include &lt;vector&gt;
  </code></pre>
  
  <p>Lastly, the main program where the function template is called:</p>
  
  <pre><code>//foo.cpp
  #include "foo.h"
  
  int main () {
  
    std::vector&lt;double&gt; v_d;
    for (int i = 0; i &lt; 10; i++) {
      v_d.push_back (i);
    }
  
    barspace::DoSomething (v_d.begin(), v_d.end());
  
    return 0;
  }
  </code></pre>
  
  <p>I compile as follows:</p>
  
  <p><code>g++ -c -o bar.o bar.cpp</code></p>
  
  <p><code>g++ -c -o foo.o foo.cpp</code></p>
  
  <p>These run fine. Now for linking:</p>
  
  <p><code>g++ bar.o foo.o -o foobar</code></p>
  
  <p>And the resulting compiler error about the undefined reference:</p>
  
  <pre><code>foo.o: In function `main':
  foo.cpp:(.text+0x6e): undefined reference to `void barspace::DoSomething&lt;__gnu_cxx::__normal_iterator&lt;double*, std::vector&lt;double, std::allocator&lt;double&gt; &gt; &gt; &gt;(__gnu_cxx::__normal_iterator&lt;double*, std::vector&lt;double, std::allocator&lt;double&gt; &gt; &gt;, __gnu_cxx::__normal_iterator&lt;double*, std::vector&lt;double, std::allocator&lt;double&gt; &gt; &gt;)'
  collect2: ld returned 1 exit status
  </code></pre>
  
  <p>There is an obvious problem with the code not getting made available from within the <code>namespace</code>, or from the <code>bar</code> compilation unit.</p>
  
  <p>Furthermore, when I try to place the definition of <code>DoSomething</code> in the <code>bar.h</code> header, as I would to circumvent the issues when defining class template methods in separate .cpp files, I get the same error.</p>
  
  <p>Can you shed some light unto my compiler linking error?</p>