[問題] (C++)關於template separation compilation model

看板C_and_CPP作者 (xie29)時間7年前 (2017/04/30 15:48), 編輯推噓2(2022)
留言24則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) macos 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) xcode 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 各位大大好,小弟為c++的初學者,現在正在看c++ primer(3rd),在template編譯模組時碰到了一點問題 ,我的目的是想要將template的宣告和定義分開,但編譯一直給我linker error的訊息,有去google了但 原因我還是看不太懂(抱歉我太菜了...),但有試過他們提供的解決方法都有效,但還是想知道為什麼無法 執行..感謝! 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): Undefined symbols for architecture x86_64: "int mmm<int>(int, int)", referenced from: _main in main.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) 程式碼(Code):(請善用置底文網頁, 記得排版) //File:Min.hpp #ifndef _MIN #define _MIN template <class Type> extern Type _min(Type , Type); #endif -- //File:Min.cpp #include "Min.hpp" template<class Type> Type _min(Type a,Type b) { return a<b?a:b; } --- //File:main.cpp #include <iostream> #include "Min.hpp" int main() { std::cout<<_min(10,20)<<std::endl; return 0; } 補充說明(Supplement): 在定義檔中沒有加上export是因為xcode不支援 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.112.17.16 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1493538494.A.961.html

04/30 16:13, , 1F
* template編譯模型 抱歉打錯了
04/30 16:13, 1F

04/30 16:34, , 2F
我猜是因為忘了角括號<>?
04/30 16:34, 2F

04/30 16:35, , 3F
<int>
04/30 16:35, 3F

04/30 16:39, , 4F
啊~剛剛查了應該不用,請無視上面的
04/30 16:39, 4F

04/30 17:47, , 5F
好的 還是感謝大大回覆
04/30 17:47, 5F

04/30 17:49, , 6F
更正:在錯誤訊息那邊的mmm就是_min,因為ㄧ開始以爲是func
04/30 17:49, 6F

04/30 17:49, , 7F
tion名稱有衝突所以隨便改ㄧ個名字
04/30 17:49, 7F

04/30 18:47, , 8F
應該不能這樣分開吧?
04/30 18:47, 8F

04/30 19:01, , 9F
你要讓template在compile time知道型態
04/30 19:01, 9F

04/30 19:12, , 10F
compiler分別編了min.o main.o但是link的時候才發現需
04/30 19:12, 10F

04/30 19:12, , 11F
要Type=int的function
04/30 19:12, 11F

04/30 21:31, , 12F
J大:不行嗎? 因為我看書上這樣教,我就實作看看了
04/30 21:31, 12F

04/30 21:35, , 13F
不過的確compiler不給我過..
04/30 21:35, 13F

04/30 21:36, , 14F
g大:感謝您的解說!非常清楚!謝謝~
04/30 21:36, 14F

05/01 01:51, , 15F
可以分只是要寫在min.cpp告訴編譯器要做int的
05/01 01:51, 15F

05/01 01:51, , 16F
或是include implement.hpp
05/01 01:51, 16F

05/01 01:51, , 17F
不過都寫template了
05/01 01:51, 17F

05/01 01:51, , 18F
自己是覺得分到cpp意義不大
05/01 01:51, 18F

05/01 12:59, , 19F
g大:那時候是想說,以後會不想公開實作檔,所以才想說試試
05/01 12:59, 19F

05/01 12:59, , 20F
,但看了網路上solution後感覺有點此地無銀三百兩..所以最
05/01 12:59, 20F

05/01 12:59, , 21F
後就覺得還是宣告跟定義寫在ㄧ起好了!! 感謝大大的回覆!很
05/01 12:59, 21F

05/01 12:59, , 22F
有幫助
05/01 12:59, 22F

05/01 13:00, , 23F
05/01 13:00, 23F

05/01 21:57, , 24F
感謝h大的回覆~
05/01 21:57, 24F
文章代碼(AID): #1P1PQ-bX (C_and_CPP)