模板链接器错误:未定义符号(链接器错误),但所有内容都在一个文件中

时间:2018-11-18 16:48:39

标签: c++ templates linker

编译并链接定义自定义文字的唯一文件失败。该文件由自定义文字定义(operator"")组成,在此之前,有一个模板类将数字(typename ... Chars)转换为NumberT类型的数字:

#include <cstdint>
#include <chrono>
#include <limits>


using Du = std::chrono::duration<uint16_t>;


template <typename NumberT, size_t Depth, char ... String>
struct _StringToNumber;

template <typename NumberT, size_t Depth, char Head, char ... Tail>
struct _StringToNumber<NumberT, Depth, Head, Tail ...> {
    static_assert('0' <= Head <= '9', "unsupported character in unsigned number literal");

    using next = _StringToNumber<NumberT, Depth+1, Tail ...>;

    const static size_t total_depth = next::total_depth;

    const static NumberT order_value = (total_depth-Depth-1)*(Head - '0');

    static_assert(std::numeric_limits<NumberT>::max() - next::value >= order_value, "literal does not fit the underlying type");

    const static NumberT value =  order_value + next::value;

};

template <typename NumberT, size_t Depth>
struct _StringToNumber<NumberT, Depth> {
    const static size_t total_depth = Depth;
    const static NumberT value = 0;
};

template <typename NumberT, char ... Chars>
using StringToNumber = _StringToNumber<NumberT, 0, Chars ...>;


template <char ... Chars>
Du operator "" _du () {  // my custom literal
    return Du(StringToNumber<Du::rep, Chars ...>::value);
}


int main() {
    1_du;  // Undefined symbols for architecture x86_64: "_StringToNumber<unsigned short, 0ul, (char)49>::value"
    StringToNumber<uint16_t, '2'>::value;  // apparently works

    return 0;
}

链接器错误:

Undefined symbols for architecture x86_64:
  "_StringToNumber<unsigned short, 0ul, (char)49>::value", referenced from:
      std::__1::chrono::duration<unsigned short, std::__1::ratio<1l, 1l> > operator"" _du<(char)49>() in scratch_1-71f359.o
ld: symbol(s) not found for architecture x86_64

奇怪的是,如果我用e替换Du和Du :: rep,我不会收到错误消息。 G。 uint16_t。

命令 g++ -std=c++17 thefile.cpp

$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 10.0.0 (clang-1000.11.45.5)
Target: x86_64-apple-darwin18.0.0
Thread model: posix

1 个答案:

答案 0 :(得分:2)

struct定义内的以下语法:

const static NumberT value = 0;

是带有初始化程序的声明,不是是定义。也就是说,编译器可以将其值用于优化目的,但是一旦value被ODR使用(例如,绑定到引用),该实体必须在内存中具有地址。通过使用std::chrono::duration作为operator""的结果,您强制value受到duration的构造函数接受作为参数的引用的约束,因此允许链接器执行以下操作:抱怨缺少定义。为了提供定义,请将以下行放在struct本身的定义之后:

template <typename NumberT, size_t Depth>
const NumberT _StringToNumber<NumberT, Depth>::value;

以及专业化之后:

template <typename NumberT, size_t Depth, char Head, char ... Tail>
const NumberT _StringToNumber<NumberT, Depth, Head, Tail ...>::value;

或进行所有声明inline):

template <typename NumberT, size_t Depth>
struct _StringToNumber<NumberT, Depth> {
    inline const static size_t total_depth = Depth;
    inline const static NumberT value = 0;
};

还请注意,标识符以下划线开头,后跟大写字母,用于实现。