constexpr静态数据成员给出未定义的引用错误 [英] constexpr static data member giving undefined reference error
问题描述
constexpr
所以我可以有一个枚举类中的值
。但是,如果我这样做,我得到一个未定义的引用错误。 工作:
pre> // terminal.hpp
class Terminal
{
static uint32_t col_map [16];
};
// terminal.cpp
uint32_t Terminal :: col_map [16] = {
0x000000,0x0000AA,0x00AA00,0x00AAAA,
0xAA0000,0xAA00AA,0xAA5500,0xAAAAAA ,
0x555555,0x5555FF,0x55FF55,0x55FFFF,
0xFF5555,0xFF55FF,0xFFFF55,0xFFFFFF
};
不工作:
// terminal.hpp
class Terminal
{
constexpr static uint32_t col_map [16] = {
0x000000,0x0000AA,0x00AA00,0x00AAAA,
0xAA0000,0xAA00AA,0xAA5500,0xAAAAAA,
0x555555,0x5555FF,0x55FF55,0x55FFFF,
0xFF5555,0xFF55FF,0xFFFF55,0xFFFFFF
};
枚举类颜色:uint32_t
{
Black = col_map [0],
White = col_map [15]
}
};
注意,我试图在常规编译器上重现这个失败,所以我认为它有关内核或交叉编译器。
链接器错误:
o:在函数`Terminal :: drawcolormap()'中:
pre>
terminal.cpp :( .text + 0x6f):未定义引用`Terminal :: col_map'
我总是运行
$ pmake clean;
解决方案静态数据成员应在类外部定义,如果它是odr使用的--- period 。此规则没有例外。
如果数据成员
constexpr
,它还必须已在 内定义类定义。
正确的代码:
$ b $class Terminal
{
constexpr static uint32_t col_map [16] = {/ * ... * /};
// ...
};
constexpr uint32_t Terminal :: col_map [16]; //定义
这是违反直觉的,但这只是它的方式。
I'm working on a kernel and I want to make my static data member
constexpr
so I can have its values in anenum class
. However, if I do so I get an undefined reference error. It only seems to work if I make it non-constexpr and initialize it outside of the class.Working:
// terminal.hpp class Terminal { static uint32_t col_map[16]; }; // terminal.cpp uint32_t Terminal::col_map[16] = { 0x000000, 0x0000AA, 0x00AA00, 0x00AAAA, 0xAA0000, 0xAA00AA, 0xAA5500, 0xAAAAAA, 0x555555, 0x5555FF, 0x55FF55, 0x55FFFF, 0xFF5555, 0xFF55FF, 0xFFFF55, 0xFFFFFF };
Not working:
// terminal.hpp class Terminal { constexpr static uint32_t col_map[16] = { 0x000000, 0x0000AA, 0x00AA00, 0x00AAAA, 0xAA0000, 0xAA00AA, 0xAA5500, 0xAAAAAA, 0x555555, 0x5555FF, 0x55FF55, 0x55FFFF, 0xFF5555, 0xFF55FF, 0xFFFF55, 0xFFFFFF }; enum class Color : uint32_t { Black = col_map[0], White = col_map[15] }; };
Note that I tried to reproduce this on a regular compiler unsuccessfully so I think it has something to do with the kernel or cross compiler.
Linker error:
terminal.o: In function `Terminal::drawcolormap()': terminal.cpp:(.text+0x6f): undefined reference to `Terminal::col_map'
I always run
make clean; make
.解决方案A static data member shall be defined outside the class if it is odr-used---period. There are no exceptions to this rule.
In the case that the data member is
constexpr
, it must also be initialized inside the class definition. However this does not abrogate the requirement to define it outside the class.Correct code:
class Terminal { constexpr static uint32_t col_map[16] = { /* ... */ }; // ... }; constexpr uint32_t Terminal::col_map[16]; // definition
It's counterintuitive, but that's just the way it is.
这篇关于constexpr静态数据成员给出未定义的引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!