[問題] link error (class, template)

看板C_and_CPP作者 (不用懂我)時間15年前 (2010/06/03 12:53), 編輯推噓0(0012)
留言12則, 3人參與, 最新討論串1/1
( *[1m *[m 為色碼,可以按 Ctrl+V 預覽會顯示的顏色 ) ( 未必需要依照此格式,文章條理清楚即可 ) 遇到的問題: (題意請描述清楚) class 當中有 template class 我試著把 inner class 當中的 function 寫到另一個 cpp 的時候 compile 沒有過 希望得到的正確結果: 希望 link 會過Orz 程式跑出來的錯誤結果: 找不到 inner class 的 constructor main.cpp:(.text+0x11): undefined reference to `outerClass::innerClass<int>::innerClass()' 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) ubuntu linux g++ 4.4.3 有問題的code: (請善用置底文標色功能) http://github.com/pcyu16/test 要看 code 也可以看下面 ============ main.cpp ============ #include "tmp.h" int main(int argc, char *argv[]) { outerClass::innerClass<int> tmp; return 0; } ================================== ============ tmp.cpp ============ #include "tmp.h" template<class T> outerClass::innerClass<T>::innerClass() { } ================================= ============ tmp.h ============ #ifndef TMP_H #define TMP_H class outerClass{ public: template <class T> class innerClass{ public: innerClass(); }; }; #endif =============================== 補充說明: 編譯指令是 g++ -c main.cpp g++ -c tmp.cpp g++ -o test main.o tmp.o 想知道是我用的方法不對還是編譯的架構不對@@" -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.116.130.5

06/03 12:57, , 1F
把 cpp 檔的東西移到 h 檔裡的話?
06/03 12:57, 1F

06/03 13:10, , 2F
定義加在 header 會過, main 裡面直接 include cpp 也會過
06/03 13:10, 2F
※ 編輯: pcyu16 來自: 140.116.130.5 (06/03 13:20)

06/03 13:22, , 3F
補上 nopaste.. 但是 github 現在好像有點慢
06/03 13:22, 3F

06/03 13:52, , 4F
這一切都是 template 搞的鬼...XDDD
06/03 13:52, 4F

06/03 13:55, , 5F
對阿= = 去掉 template 好像就沒事了Orz
06/03 13:55, 5F

06/03 14:34, , 6F
class template 的 member function 是有用到才會
06/03 14:34, 6F

06/03 14:34, , 7F
instantiate 出來,而且是很主觀的用編譯單元判定。
06/03 14:34, 7F

06/03 14:35, , 8F
編譯 tmp.cpp 的時候,compiler 沒看到任何 code 用到
06/03 14:35, 8F

06/03 14:35, , 9F
outerClass::innerClass<int>::innerClass(),
06/03 14:35, 9F

06/03 14:36, , 10F
所以不會產生出來,link 的時候當然也沒有這東西。
06/03 14:36, 10F

06/03 14:37, , 11F
所以請把定義式放在 .h 裡,或是用支援 export keyword 的
06/03 14:37, 11F

06/03 14:37, , 12F
compiler,然後在 tmp.cpp 的函式定義前標上 export。
06/03 14:37, 12F
文章代碼(AID): #1C1pLSrL (C_and_CPP)