我想使用该 struct 来存储一些数据,然后通过DMA传输它.然而,外围设备的细节要求沿着4字节边界对齐 struct 的初始地址.我不明白为什么在不同的地方使用alignment属性会导致压缩 struct 的大小被调整1个字节.
我写了一个简单的例子来说明这种情况.
#include <stdio.h>
#include "stdint.h"
// Version with aligned attribute
struct packet_v1
{
uint8_t uid;
uint8_t flag;
uint8_t comm;
uint32_t a;
} __attribute__((packed, aligned(4)));
// Version without alignment
struct packet_v2
{
uint8_t uid;
uint8_t flag;
uint8_t comm;
uint32_t a;
} __attribute__((packed));
struct packet_v1 pkt1;
struct packet_v2 pkt2 __attribute__((aligned(4)));
int main()
{
printf("Align v1: %lu, size: %lu\r\n", (uintptr_t)&pkt1 % 4, sizeof(pkt1));
printf("Align v2: %lu, size: %lu\r\n", (uintptr_t)&pkt2 % 4, sizeof(pkt2));
return 0;
}
输出:
Align v1: 0, size: 8
Align v2: 0, size: 7