https://wandbox.org/permlink/skxmougiYnaw1f1a
一开始遭遇到这个compile warning
warning: instantiation of variable 'Foo<int>::bar' required here, but no defin
ition is available [-Wundefined-var-template]
其实我不太知道他为什么会warning
我确实有define在test.cpp这个translation unit
不懂的是 他感觉找不到定义 却让我pass, run time 也有拿到对的数值.
而g++不会有warning
1. 到这边我还是不知道到底哪里写的不够正确?
然而我试着解决这warning
于是我把 上面的
//b.
// extern template class Foo<int>;
打开
https://wandbox.org/permlink/j2ANWRBoeIZZJAHE
link error
undefined reference to `Foo<int>::Test()'
如果不呼叫 这个warning确实可以这样解决
但我必须呼叫这function
2. 为什么他这样会说undefined? .h里面明确有包含定义阿?
然而
//a.
// template class Foo<int>;
打开后
3. 我认为我已经明确让他产生程式码了.... warning还是存在
回归1. 的问题 我到底少做了什么让clang这样出warning
4. 对于template class内 有static function or data
最正确的写法该怎么写.
网络上有查到
在test.h 直接写
template<class T>
int Foo<T>::bar = 初始直;
test.cpp一样写
template<>
int Foo<int>::bar = 123;
但我实际上在专案遇到一个况状是
我某个cpp 写Foo<int>::bar 拿到的却是.h给的初始直(我认为是他初始化顺序优先于te
st.cpp)
所以目前毫无办法处理这warning
5. 这似乎没办法用static是internal linkage 来解释...让我整个无法通透理解
请教各位有什么方法处理这问题
谢谢
你对bar做模板特化 并不会帮你生整个class所以test.cpp要补Test()的特化; 你的extern才抓的到3跟4我不确定 感觉是undefined behavior 要查一下XD
作者: AstralBrain 2018-06-23 00:19:00
作者: AstralBrain 2018-06-23 02:07:00
static member本来就是external linkage吧static variable和static member是不一样的(虽然他们都叫static..)
谢谢,只是这个warning 我在编译出binary后如果没改程式码再编一次就没有warning了,为什么呢
作者: AstralBrain 2018-06-23 23:08:00
因为没有真的compile到? (乱猜的XD)
incremental building 你re-compile或cleanup就有了
但这warning到底会不会对程式本身有可能有错误的风险呀?不理他感觉也没怎样
他无法判断会不会 比方说有个warning是not all control paths return a value 这个就是会让你过 但是你是有可能有runtime issuey但是有些则是完全是murmur 这要自己判断一下