The forward-declaring template variable will cause ld error.
#include <iostream>
template<class T> extern int a;
template<class T> int a = 1;
int main()
{
std::cout << a<int> << a<float>;
return 0;
}
$ LANG=C g++ main.cpp -o main
/usr/bin/ld: /tmp/cccOb25F.o: in function `main':
main.cpp:(.text+0x6): undefined reference to `a<int>'
/usr/bin/ld: main.cpp:(.text+0x1d): undefined reference to `a<float>'
collect2: error: ld returned 1 exit status
However, the forward-declaring variable (without template) and the forward-declaring template function works fine.
#include <iostream>
extern int a;
int a = 1;
template<class T> int b();
template<class T> int b()
{
return 2;
}
int main()
{
std::cout << a << b<int>();
return 0;
}
So, is it possible to make the forward-declaring template variable in C++ works?
EDIT:
Since clang++ works fine, maybe I accidentally found a bug of g++?
EDIT2:
I have found a bug report about 2.5 years ago (here), which is exactly the same problem. Oh, we need a guy who could read gcc source and fix it...