2013-05-14 42 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&)' 我真的不知道我從未聽說過的額外旗幟是否有所作爲。 –