如何将C结构与4字节边界对齐



我有以下结构:

typedef struct LOG_EVENT
{
    time_t time;
    uint32_t count;
    int32_t error_type;
    uint16_t gm_state;
    uint8_t gm_mode;
    uint8_t mc_state;
} LOG_EVENT;

在32位系统上,结构的strict alignment为4个字节,因此成员在4字节边界上进行对齐。在这种情况下,没有添加填充物,因为所有成员均为4字节对齐。

,但这在64位系统上不是正确的,其中time_t为64位。在这种情况下,strict alignment为8字节。

如何将对齐方式更改为4字节?我想在64位系统的4个字节边界上对齐,因为我想确保没有完成填充。

从GCC属性页https://gcc.gnu.org/onlinedocs/gcc-3.2/gcc-3.2/gcc/variable-attributes.html,它说 The aligned attribute can only increase the alignment; but you can decrease it by specifying packed as well

我看不到 packed属性接受任何参数。

另外,如果我使用以下字节对准,则与4字节对齐相比会引起任何问题:

typedef struct __attribute__ ((packed)) LOG_EVENT
{
    time_t time;
    uint32_t count;
    int32_t error_type;
    uint16_t gm_state;
    uint8_t gm_mode;
    uint8_t mc_state;
} LOG_EVENT;

#pragma pack(4)将将对齐设置为4个字节。

请注意,该指令不是标准的一部分,最初是在MSVC中引入的,后来被GCC通过以与Microsoft的编译器相兼容。

另外,请注意time_tsize_t等类型的大小和所有指针类型在这些体系结构之间都会有所不同。如果您的意图是在这两个体系结构上运行的应用程序之间可理解的结构,这将是一个问题。

还知道,使用64位应用程序没有任何好处那个罪。

最直接的事情是...不使用time_t。仅使用固定宽度类型。

typedef struct LOG_EVENT
{
    int32_t time;
    uint32_t count;
    int32_t error_type;
    uint16_t gm_state;
    uint8_t gm_mode;
    uint8_t mc_state;
} LOG_EVENT;

您放弃了在签名的32位time_t范围之外处理时间戳的能力(通常但并非总是如此,1901-12-13T20:45:45:52Z至2038-01-19T03:14:07Z),但是如果您'试图使用32位时间戳的盘录记录阵列,这是这里最合理的解释,这不是问题。

最新更新