未定义的引用指针的变量模板在clang中功能,而不是GCC

undefined reference to variable template of pointer to function in clang but not gcc

本文关键字:功能 GCC 指针 引用 变量 未定义 clang      更新时间:2023-10-16
#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有一个使用变量模板的项目,该模板本身就是用于功能的指针。上面的示例代码在GCC 6.3中编译并执行正常,但在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:msys64tmpSource-6600e8.o:(.text+0x2a): undefined reference to `fp<int>'
clang++.exe: error: linker command failed with exit code 1 (use -v to see invocation)

任何帮助都将不胜感激。

首先必须初始化fp&lt;>():

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

它在Clang 4.0:示例代码中编译并运行良好。并尝试始终初始化您的变量 - 它可能会使您免于各种头痛。:)