Search code examples
c++linkervariable-templates

Variable template fails to link


The following code:

template<typename T>
constexpr T foo { 1.2345 };

template<typename T>
T fun(T x) {
  return -foo<T> * x;
}

int main() {
  fun(2.0);
}

compiled using gcc version 5.1.0 on Linux

g++ gcc-bug.cpp -std=c++14

fails during the linking step with the following message:

/tmp/ccuciovi.o: In function `double fun<double>(double)':
gcc-bug.cpp:(.text._Z3funIdET_S0_[_Z3funIdET_S0_]+0xd): undefined reference to `foo<double>'
collect2: error: ld returned 1 exit status

Removing the unary minus (which changes the meaning of the code), gets rid of the linking error. Prepending zero (which does not change the meaning of the code) also gets rid of the error. The following two implementations of foo lead to a successful compilation:

template<typename T>
T fun(T x) {
  return foo<T> * x; // different meaning
}

template<typename T>
T fun(T x) {
  return 0 - foo<T> * x; // same meaning
}

I do not observe this behavior in other compilers. The original code (with the unary minus) compiles and runs fine using clang 3.6.0 and gcc 5.2.0.

Before I submit this as a bug in gcc 5.1.0 I'd like to hear your take on this behavior.


Solution

  • runs fine using ... gcc 5.2.0

    Possibly https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65719