Undefined reference to function pointer variable template in clang, but not gcc

#include <iostream>

static constexpr bool isSSE2 = true;

template<typename T>
static void (*fp)();

template<typename T>
static void foo_c() {
    std::cout << "foo_c get called." << std::endl;
}

template<typename T>
static void foo_sse2() {
    std::cout << "foo_sse2 get called." << std::endl;
}

int main() {
    if (isSSE2)
        fp<int> = foo_sse2<int>;
    else
        fp<int> = foo_c<int>;

    fp<int>();

    return 0;
}

I have a project that uses a variable template, which itself is a pointer to a function. The code example above compiles and runs fine in GCC 6.3, but gives a warning and error in clang 3.9.1.

$ clang++ "Source.cpp" -o "foo.exe" -std=c++14 -O2
Source.cpp:6:15: warning: variable 'fp<int>' has internal linkage but is not defined [-Wundefined-internal]
static void (*fp)();
              ^
Source.cpp:20:9: note: used here
        fp<int> = foo_sse2<int>;
        ^
1 warning generated.
C:\msys64\tmp\Source-6600e8.o:(.text+0x2a): undefined reference to `fp<int>'
clang++.exe: error: linker command failed with exit code 1 (use -v to see invocation)

Any help is appreciated.

+4
source share
1 answer

First you must initialize fp <> ():

template<typename T>
static void (*fp)() = nullptr;

It compiles and works great in Clang 4.0: sample code . And try to always initialize your variables - this can save you from any headaches. :)

+3
source

Source: https://habr.com/ru/post/1671566/


All Articles