【发布时间】:2015-10-07 21:14:40
【问题描述】:
我使用这种形式的 typedef 来简化对微处理器寄存器和其中位字段的访问。
typedef union
{
uint8_t u8Byte; ///< REG_8 as unsigned byte
int8_t i8Byte; ///< REG_8 as signed byte
struct
{
unsigned b0:1; ///< Bit 0 of REG_8 type
unsigned b1:1; ///< Bit 1 of REG_8 type
unsigned b2:1; ///< Bit 2 of REG_8 type
unsigned b3:1; ///< Bit 3 of REG_8 type
unsigned b4:1; ///< Bit 4 of REG_8 type
unsigned b5:1; ///< Bit 5 of REG_8 type
unsigned b6:1; ///< Bit 6 of REG_8 type
unsigned b7:1; ///< Bit 7 of REG_8 type
};
} REG_8;
不幸的是,sizeof(REG_8) 返回 2 而不是预期的 1。REG_16 和 REG_32 的类似定义返回大小为 2 和 4,正如预期的那样。 sizeof(uint8_t) 和 sizeof(int8_t) 按预期返回 1。
该类型按预期工作。例如,
REG_8 a;
a.u8Byte = 4;
将a.b2 的值设为1,因此不存在对齐问题。
删除 struct 后,sizeof 的值为 1,因此看起来存在填充问题,但如果是,为什么?
谁能解释一下?我正在使用针对 16 位处理器的 Microchip XC16 编译器(基于 GCC)。
【问题讨论】:
-
我的猜测是,由于严格的数据对齐寻址,您的 16 位机器将为您的一字节联合使用 1 字节填充。这是一个猜测,因为我不熟悉机器/编译器。
-
@IanGabes 在这台 16 位机器上,字确实需要在偶数地址上对齐,但是机器可以访问任何地址的字节(即,没有对齐要求)
标签: struct sizeof unions bit-fields xc16