我正在使用模板在C++中實現哈希表和鏈接列表(沒有STL - 不要問),而且我遇到了將它們與g ++鏈接起來的問題。如果我把所有的.cpp文件包括在一起,一切都可以正常工作,所以我的代碼肯定有效,這只是讓我絆倒的鏈接。使用g ++鏈接模板
我讀the bit in the GCC manual about template instantiation,但不知道如何應用它。
我的問題: 我有我的哈希表HashMap<T>
和HashEntry<T>
(<T>
是價值 - 我的鑰匙是std::string
S)。我的鏈接列表有LinkedList<T>
和Node<T>
(其中<T>
是值)。
在我的哈希表,我有:
template <class T> class HashMap {
...
private:
LinkedList< HashEntry<T> >** buckets;
}
這給了我的HashEntry<T>
個鏈表。
在一個單獨的文件,我有我的鏈表類的聲明:
template <class T>
class Node {
...
private:
T data;
}
template <class T> class LinkedList {
...
private:
Node<T> * first;
}
然後,當我嘗試(與g++ -c -frepo *.cpp
編譯後)鏈接的一切,我得到:
g++ -frepo -o app LinkedList.o HashMap.o
[...unrelated errors about not having a main method - they go away when I link that in]
HashMap.o: In function `HashMap<int>::~HashMap()':
HashMap.cpp:(.text._ZN7HashMapIiED1Ev[HashMap<int>::~HashMap()]+0x65): undefined reference to `LinkedList<HashEntry<int> >::~LinkedList()'
HashMap.o: In function `HashMap<int>::insert(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int)':
HashMap.cpp:(.text._ZN7HashMapIiE6insertESsi[HashMap<int>::insert(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int)]+0xff): undefined reference to `Node<HashEntry<int> >::setData(HashEntry<int>)'
谷歌搜索在我看來,我的程序使用了顯式模板類型的建議。該方法適用於HashMap
和HashEntry
(我加(template class HashMap<int>
和template class HashEntry<int>
。
然而,我無法弄清楚如何使這項工作爲LinkedList
和Node
類,因爲模板實例是HashEntries<int>
,但是,我可以't把它放到LinkedList.h
文件中,因爲它是我的哈希表的#include
d。我也無法得到一個高級/ extern聲明。
我敢肯定,有一些相當簡單的東西我失蹤使所有這些工作。任何提示?
是否有你的`LinkedList`析構函數的定義在任何地方?或`節點<...> :: setData()`? – robert 2010-12-22 00:04:20
也許不相關,但是有什麼理由不使用make,waf,SCons等。 – robert 2010-12-22 00:05:21