c++元组链接问题:未定义的引用

C++ tuple linking issue: undefined reference

本文关键字:未定义 引用 问题 元组 链接 c++      更新时间:2023-10-16

我认为这段代码有严重的错误。它将编译,但不会被链接。

#include <iostream>
#include <tuple>
class Table_class
{
    public:
    constexpr static std::tuple<int, unsigned int, unsigned short> table[3]
    = {std::make_tuple(1, 2, 3),
        std::make_tuple(4, 5, 6),
        std::make_tuple(7, 8, 9)};
};
int main()
{
    std::cout << std::get<0>(Table_class::table[0]);
    return 0;
}

显示的错误如下:

[31m/tmp/ccDiIuPv.o: In function `main':
file.cpp:(.text+0x5): undefined reference to `Table_class::table'
collect2: error: ld returned 1 exit status
Compilation Failed

如何纠正?

这并不是大错特错。你的代码在c++ 17中是(将是)完全合法的。然而,在c++ 17之前,静态constexpr数据成员需要在类的外部定义,因此找到某个地方并添加以下定义:

constexpr std::tuple<int, unsigned int, unsigned short> Table_class::table[3];

演示。

通常,变量定义不应该在头文件中。

这是链接错误的常见来源。您必须在类定义之外定义表,以使链接器找到它。一个简单的例子:

#include <iostream>
#include <tuple>
class Table_class
{
    public:
    constexpr static std::tuple<int, unsigned int, unsigned short> table = std::make_tuple(1, 2, 3);
};
constexpr std::tuple<int, unsigned int, unsigned short> Table_class::table;
int main()
{
    std::cout << std::get<0>(Table_class::table);
    return 0;
}