G++ 尚未支援 extern template?
在用別人實作的 Graph Cuts 的時候,發現原來 g++(以 4.3.1 實測)似乎尚未支援 extern template:如果 function template 的定義跟宣告拆開來的話,會出現 undefined reference error。儘管按照這份 spec 應該是 OK 的。或許中間出了什麼差錯,晚點再試試。
暫時的解決方式很簡單,把所有定義丟到 header file 裡面去就行了。
. 30 Nov 08 | C++



雖然我沒看過 Jonathan 說的 graph cuts library 的 source code. 但我猜 Jonathan 沒把一些東西搞得夠清楚.
首先 GCC 不可能沒支援 “template function” linking”. 所謂 template function, 不過就是 function template 被 instantiate 的實體, 其 linking 方法與規則基本上與一般 old-school function 無異. 以上為 “template function” 與 “function template” 搞混的部份.
另, 把 template function 的 definition 放在 source files (instead of header files) 叫作 “extern template“. 就我所知沒有任何主流 compiler 支援這項 feature, e.g. g++ (however, g++ 4.3/4.4 supports this feature) and MSVC. 並, 其 declaration 的方法與一般的 template 不同, 需要加上 “extern” keyword. 由於 Jonathan 沒提到 “extern”, 因此我猜說的狀況應該也不是 “extern template”.
extern template
感謝指教,看來我是搞混了,我的狀況是 extern template。我等會兒把文章修改一下。
不過 g++ 4.3 以上就支援了嗎?我測的狀況似乎還是不行。(4.3.1 on Ubuntu 8.04)。
AFAIK, extern template 只是一種 compiler 與 linker 合作的 hack.
即便已編譯成 library, 當 library source 內有 extern template 時, client code 依然需要該 extern template 的 source code 才能 link 到 template 的 instance.
因此我對 extern template 沒有好感. 也懶得去試.
> 如果 template function 的定義跟宣告拆開來的話
應為:
如果 function template 的定義跟宣告拆開來的話
Function template 為 template 本身, 出現於 source code.
Template function 是 compile time 時 function template 具現化的結果, 不存在於 source code.
原來如此,不過的確 header file 跟 implementation file 有時是有分開的必要,那麼,對 function template 來說又該怎麼作比較好?
寫在 COdE fr3@K 的回應.
寫在 COdE fr3@K 的回應.