This problem is the definition and declaration of the function template in the namespace, which is defined in the external file where this function is created from. Here is the smallest reproducible example that I could come up with. 4 files:
Declaring a function template in a named namespace:
// bar.h #include <algorithm> namespace barspace { template <typename Iter> void DoSomething (Iter first, Iter last); }
Function template definition in a separate file:
// bar.cpp #include "bar.h" namespace barspace { template <typename Iter> void DoSomething (Iter first, Iter last) { typedef typename std::iterator_traits<Iter>::value_type val_t; std::sort (first, last); } } // namespace barspace
Main program title
// foo.h
Finally, the main program where the function template is called:
//foo.cpp
I am compiling the following:
g++ -c -o bar.o bar.cpp
g++ -c -o foo.o foo.cpp
They work fine. Now for the link:
g++ bar.o foo.o -o foobar
And the resulting compiler error regarding the undefined link:
foo.o: In function `main': foo.cpp:(.text+0x6e): undefined reference to `void barspace::DoSomething<__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > > >(__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >, __gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >)' collect2: ld returned 1 exit status
There is an obvious problem with the fact that the code does not become accessible from namespace or from the compilation unit bar .
Also, when I try to put the DoSomething definition in the bar.h header, since I would get around problems when defining class template methods in separate .cpp files, I get the same error.
Can you shed some light on my compiler's communication error?