templates - C++ undefined reference to a linked function -


i have problem linking of c++ project , can't figure out what's wrong. jest of code.

clitest.cpp

#include <iostream> #include "node.h" using namespace std;  int main(int argc, char** argv) {     node<int> *ndnew = new node<int>(7);     return 0; } 

node.h

#ifndef node_h #define node_h #include <vector>  template <typename t> class node {     private:         node<t>* ndfather;         std::vector<node<t>* > vecsons;     public:         t* data;         node(const t &data); }; #endif 

node.cpp

#include "node.h"  using namespace std;  template <typename t> node<t>::node(const t &data) {     this->data = &data;     this->ndfather = 0;     this->vecsons = (new vector<t>()); }; 

the compiler command used is

g++ -wall -g clitest.cpp node.cpp -o clitest 

the error log goes this

clitest.cpp: in function ‘int main(int, char**)’: clitest.cpp:8:16: warning: unused variable ‘ndnew’ [-wunused-variable]      node<int> *ndnew = new node<int>(7);                 ^ /tmp/cc258ryg.o: in function `main': clitest.cpp:8: undefined reference `node<int>::node(int const&)' collect2: error: ld returned 1 exit status make: *** [blist] error 1 

i have spent decent amount of time shifting code around, trying identify problem , either miss basic, or it's don't know c++ linkage.

when using templates, compiler needs know how generate code class when instantiated. undefined reference error caused because compiler did not generate node<int>::node(int const &) constructor. see, e.g. why can templates implemented in header file?

you have couple of options:

  1. put implementation in node.h (node.cpp removed not needed)
  2. put implementation in file #included @ bottom of node.h (usually file called node.tpp)

i suggest putting implementation in node.h , removing node.cpp. note code in example not valid c++: member variable vecsons not pointer line vecsons = new vector<t>() give compiler error. following code starting point full implementation:

#ifndef node_h #define node_h #include <vector>  template <typename t> class node {     private:         node<t>* ndfather;         std::vector<node<t>* > vecsons;     public:         const t* data;         node(const t &d) :              ndfather(0),             vecsons(),             data(&d)         {         } }; #endif 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -