2013-05-14 38 views
1

我有一个C++项目链接的问题,我无法弄清楚什么是错的。 代码的笑话。C++未定义的引用链接功能

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>()); 
}; 

的是使用编译器指令是

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

错误日志是这样的

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 to `node<int>::node(int const&)' 
collect2: error: ld returned 1 exit status 
make: *** [blist] Error 1 

我已经花了很多时间像样的量左右移位的代码,试图找出问题,我要么会错过一些基本的东西,或者这件事情我不知道C++链接。

+0

可能重复的[为什么模板只能在头文件中实现?](http://stackoverflow.com/questions/495021/why- –

回答

0

当使用模板时,编译器需要知道如何当它被实例化生成的类的代码。未定义的引用错误是由于编译器未生成构造函数node<int>::node(int const &)而引起的。参见例如Why can templates only be implemented in the header file?

你有两个选择:

  1. 把实施node.h(node.cpp被删除,因为它不需要)
  2. 将是在执行#included在一个文件中执行node.h的底部(通常该文件将被称为node.tpp)

我建议在Node.h中执行该实现并删除node.cpp。请注意,示例中的代码无效C++:成员变量vecSons不是指针,因此行vecSons = new vector<T>()会给出编译器错误。下面的代码可能是完整实现的起点:

#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 
+0

通过使用标头唯一的方法解决(我个人不喜欢)。 –

0

在.cpp文件之前使用-I.,以便编译器知道要查找.h文件。

g++ -Wall -I. clitest.cpp node.cpp -o clitest 

或者只是-I

g++ -Wall -I clitest.cpp node.cpp -o clitest 
+0

链接器的答案为:clitest.cpp :(。text + 0x31):未定义的引用“节点 :: node(int const&)' 我真的不知道我从未听说过的额外旗帜是否有所作为。 –