pragma pack(1)或__attribute__((aligned(1)))都有效 [英] pragma pack(1) nor __attribute__ ((aligned (1))) works

查看:427
本文介绍了pragma pack(1)或__attribute__((aligned(1)))都有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码过去曾经可以工作,但是现在结构大小突然变为16个字节.过去是13个字节.我最近从Xcode 4.2升级到Xcode 4.3.1(4E1019).

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

我尝试使用未成功

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

如何使用Xcode 4.3.1打包结构?

推荐答案

Xcode使用gccclang编译器,它们都使用__attribute__((packed))来指定结构打包.

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

使用__attribute__((aligned(1)))告诉编译器在下一个字节边界开始每个struct元素,但没有告诉它在末尾可以放置多少空间.这意味着允许编译器将struct舍入为机器字大小的倍数,以更好地用于数组和类似内容中. __attribute__((packed))告诉编译器甚至在struct的末尾根本不使用任何填充.

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.

这篇关于pragma pack(1)或__attribute__((aligned(1)))都有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆