我在定义为的头文件中构建了一个使用常量的工作 C 库
typedef struct Y {
union {
struct bit_field bits;
uint8_t raw[4];
} X;
} CardInfo;
static const CardInfo Y_CONSTANT = { .raw = {0, 0, 0, 0 } };
我知道.raw初始化程序是仅限 C 的语法。
如何在其中定义带有联合的常量,以便我可以在 C 和 C++ 中使用它们。
我在定义为的头文件中构建了一个使用常量的工作 C 库
typedef struct Y {
union {
struct bit_field bits;
uint8_t raw[4];
} X;
} CardInfo;
static const CardInfo Y_CONSTANT = { .raw = {0, 0, 0, 0 } };
我知道.raw初始化程序是仅限 C 的语法。
如何在其中定义带有联合的常量,以便我可以在 C 和 C++ 中使用它们。
我相信 C++11 允许您像这样编写自己的构造函数:
union Foo
{
X x;
uint8_t raw[sizeof(X)];
Foo() : raw{} { }
};
这默认初始化类型Foo为活动成员的联合raw,其中所有元素均为零初始化。(在 C++11 之前,无法初始化不是完整对象的数组。)
我决定选择以下路径。
.member初始化。static const struct Foobar成员的初始化而是声明全局变量:
extern "C" {
extern const struct Foobar foobar;
}
并在全局部分中对其进行初始化:
struct Foobar foobar = { 0, 0, 0, 0 };
而不是使用现代 ANSI C99 语法来干扰 C++ 编译器,我让链接器完成对 C 符号进行解构的工作。