结构体对齐

My code used to work in the past, but now the struct size suddenly is 16 bytes. It used to be 13 bytes. I recently upgraded from Xcode 4.2 to Xcode 4.3.1 (4E1019).

#pragma pack(1)
struct ChunkStruct {
    uint32_t width;
    uint32_t height;
    uint8_t bit_depth;
    uint8_t color_type;
    uint8_t compression;
    uint8_t filter;
    uint8_t interlace;
};
#pragma pack()
STATIC_ASSERT(expected_13bytes, sizeof(struct ChunkStruct) == 13);

I have tried unsuccesfully using

#pragma pack(push, 1)
/* struct ChunkStruct { ... }; */
#pragma pack(pop)

I have also tried the following, but no luck

struct ChunkStruct {
    uint32_t width;
    uint32_t height;
    uint8_t bit_depth;
    uint8_t color_type;
    uint8_t compression;
    uint8_t filter;
    uint8_t interlace;
} __attribute__ ((aligned (1)));

How to pack structs with Xcode 4.3.1 ?

share improve this question
 

1 Answer

up vote 20 down vote accepted

Xcode uses the gcc and clang compilers which both use __attribute__((packed)) to designate struct packing.

struct foo {
  uint8_t bar;
  uint8_t baz;
} __attribute__((packed));

Using __attribute__((aligned(1))) tells the compiler to begin each struct element on the next byte boundary but doesn't tell it how much space it can put at the end. This means that the compiler is allowed to round the struct up to a multiple of the machine word size for better use in arrays and similar. __attribute__((packed)) tells the compiler to not use any padding at all, even at the end of the struct.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值