[問題] template 編譯錯誤

看板C_and_CPP (C/C++)作者 (gigigigi)時間9年前 (2016/09/22 22:47), 9年前編輯推噓3(3019)
留言22則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux/g++ // 將 template 宣告在 quaternion.h , 函數實作在 quaternion.cpp https://gist.github.com/anonymous/00090f1598973c1c924afebf88199cc9 這樣編譯下面錯誤 g++ main.cpp quaternion.cpp -o main /tmp/ccnOQeym.o: In function `main': main.cpp:(.text+0x27): undefined reference to `Quaternion<float>::Quaternion()' main.cpp:(.text+0x38): undefined reference to `Quaternion<float>::~Quaternion()' collect2: error: ld returned 1 exit status 我把template 宣告跟實做都集中在 quaternion.h 可以編譯過 https://gist.github.com/anonymous/21a12dfedf6982b963d249f890977aaf g++ main.cpp -o main 請問這是什麼原因造成? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 175.182.180.254 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1474555677.A.11B.html ※ 編輯: gigigigi (175.182.180.254), 09/22/2016 22:48:27

09/22 23:07, , 1F
所以是指一開始沒把實作include到main.cpp會error嗎?
09/22 23:07, 1F

09/22 23:07, , 2F
這是因為編譯main.cpp的時候需要有template的實作,
09/22 23:07, 2F

09/22 23:08, , 3F
用來產生Quaternion<float>這個class吧
09/22 23:08, 3F

09/22 23:11, , 4F
gcc -c main.cpp 可以過~上面錯誤應該是link 階段出錯
09/22 23:11, 4F
※ 編輯: gigigigi (175.182.180.254), 09/22/2016 23:13:00

09/22 23:13, , 5F
g++ main.cpp quaternion.cpp -o main 也有把
09/22 23:13, 5F

09/22 23:14, , 6F
quaternion 實作編譯出來但 link 出錯
09/22 23:14, 6F

09/22 23:36, , 7F
https://goo.gl/GW1ma0 最簡單的方法是都放到.h檔
09/22 23:36, 7F

09/22 23:37, , 8F
template實作要跟定義寫在同個檔裡
09/22 23:37, 8F

09/22 23:37, , 9F
宣告
09/22 23:37, 9F

09/22 23:38, , 10F
https://goo.gl/ZaAepL 或是參考這個 兩個都有寫原因
09/22 23:38, 10F

09/22 23:38, , 11F
我是那悶這樣拆問什麼 link 階段會失敗.. 因為這程式碼
09/22 23:38, 11F

09/22 23:39, , 12F
是拆成h & cpp 檔案..
09/22 23:39, 12F

09/22 23:40, , 13F
我的理解是編譯Q.cpp的時候 不會知道要編出Q<float>
09/22 23:40, 13F

09/22 23:41, , 14F
你在.cpp加個template class Q<float>; 應該就會對了
09/22 23:41, 14F

09/22 23:43, , 15F
Q.cpp沒有編譯出Q<float>的實作 所以main.cpp
09/22 23:43, 15F

09/22 23:43, , 16F
就會出現link error
09/22 23:43, 16F

09/22 23:49, , 17F
不過一般都是全部放到.h檔 stl的容器也都是這樣
09/22 23:49, 17F

09/23 00:24, , 18F
我大概懂了,template 是編譯階段看宣告type 去覺的產生
09/23 00:24, 18F

09/23 00:25, , 19F
對應 type class ...
09/23 00:25, 19F

09/23 04:02, , 20F
你可以在你的quaternion.cpp 最後面寫上
09/23 04:02, 20F

09/23 04:02, , 21F
template class Quaternion<float>;
09/23 04:02, 21F

09/23 04:03, , 22F
應該就可以了
09/23 04:03, 22F
文章代碼(AID): #1Nu-yT4R (C_and_CPP)
文章代碼(AID): #1Nu-yT4R (C_and_CPP)