c++元组链接问题:未定义的引用
C++ tuple linking issue: undefined reference
我认为这段代码有严重的错误。它将编译,但不会被链接。
#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;
}
相关文章:
- 对C宏的未定义引用,但在定义它时会出现重新定义错误
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 对Py_Initialize()的未定义引用
- 使用mysql c++连接器的未定义引用
- 对 Scalar ::Scalar() 的未定义引用
- 对复制 CTOR 和 CTOR 的未定义引用
- 对显式实例化的模板函数的未定义引用
- TensorRT (C++ API) 对"createNvOnnxParser_INTERNAL"的未定义引用
- 2个模板化类的非模板友元函数未定义引用错误
- 编译 libfluid 样本控制器时对"event_base_del_virtual"的未定义引用
- 获取对function_name的未定义引用
- 对 'std::thread::_M_start_thread CMake 的未定义引用进行基准测试
- 对结构方法的未定义引用
- 使用内联函数 c++ 的未定义引用
- 对 CMake 中'cudaRegisterLinkedBinary'链接错误的未定义引用?
- 对 DLOPEN 的未定义引用
- QT C++中对全局变量的未定义引用
- 快速数学导致对"__pow_finite"的未定义引用
- 对 boost::system::d etail::system_category_instance 的未定义引用,从
- OpenCV 3.4.3 中对 'cv::String::d eallocate()' 错误的未定义引用