c++ - Templated function being reported as "undefined reference" during compilation -


these files:

--------[ c.hpp ]--------

#ifndef _c #define _c  #include<iostream> class c { public:     template<class cartype> void call(cartype& c); };  #endif 

--------[ c.cpp ]--------

#include "c.hpp"  template<class cartype> void c::call(cartype& c) {     //make use of c somewhere here     std::cout<<"car"<<std::endl; } 

--------[ v.cpp ]--------

class merc {}; 

--------[ main.cpp ]--------

#include "c.hpp" #include "v.cpp" //#include "c.cpp"  int main() {     merc m;      c somecar;     somecar.call(m);  }//main 

i'm able generate ".o" files above files, command g++ -c main.cpp , g++ -c c.cpp , on. when try linking ".o" files g++ -o car c.o main.o v.o error:

main.o: in function `main': main.cpp:(.text+0x17): undefined reference `void c::call<merc>(merc&)' collect2: ld returned 1 exit status 

the error goes away when uncomment line #include "c.cpp" in main.cpp, feel may bad practice include cpp file way. doing wrong? there better way cater templated declarations while creating separate object files , linking them? p.s: i'm using templated function in more complex class structure. shown here small example sake of showing kind of error i'm facing.

a way solve problem

a. remove '#include "c.hpp"' c.cpp and

b. include 'c.cpp' @ end of 'c.hpp' (strange sounding '#include "c.pp"')

this way template definitions availabe each translation unit includes 'c.hpp' without explicitly doing in each .cpp file. called 'inclusion model'


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -