pragma pack(1)与__attribute__((aligned(1)))均无效

20

我的代码过去能够正常工作,但现在结构体的大小突然变成了16字节。它曾经是13字节。我最近从Xcode 4.2升级到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);

我尝试过使用,但没有成功

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

我也尝试了下面的方法,但没有成功

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)));

如何在Xcode 4.3.1中打包结构体?

1个回答

31

Xcode使用gccclang编译器,它们都使用__attribute__((packed))指定结构体的打包方式。

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

使用__attribute__((aligned(1)))告诉编译器在下一个字节边界上开始每个结构元素,但不告诉它可以在结尾放置多少空间。这意味着编译器允许将struct舍入到机器字大小的倍数,以便更好地用于数组等。而__attribute__((packed))则告诉编译器完全不使用填充,即使在struct末尾也是如此。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接