结构字节对齐问题XCode 4.3

时间:2012-05-24 04:35:27

标签: objective-c xcode struct alignment

我正在尝试使用struct来映射BitMap文件的标头。似乎编译器正在进行4字节(32位)对齐,但我需要2Byte。我试图通过complier指令改变它,如下所示

#pragma pack(2)

__attribute__ ((aligned(xx)));

这两个似乎没有任何影响。还有另一种方法吗? 我在Mac OS X Lion上使用XCode 4.3。我测试了Apple LLVM和Apple GCC编译器。

这是Struct类型定义

typedef struct {
    int16_t bfType; 
    int32_t bfSize;
    int16_t bfReserved1;
    int16_t bfReserved2;
    int32_t bfOffBits;
    int32_t biSize;
    int32_t biWidth;
    int32_t biHeight;
    int16_t biPlanes;
    int16_t biBitCount;
    int32_t biComression;
    int32_t biSizeImage;
    int32_t biXPelsPerMeter;
    int32_t biYPelsPerMeter;
    int32_t biClrUsed;
    int32_t biClrImportant;
} THeader;

1 个答案:

答案 0 :(得分:2)

咦?适用于我的机器?请记住,pack pragma可能在其他地方被覆盖了?

#include <inttypes.h>
#include <stddef.h>

#pragma pack(push,2)

typedef struct {
int16_t bfType; 
int32_t bfSize;
int16_t bfReserved1;
int16_t bfReserved2;
int32_t bfOffBits;
int32_t biSize;
int32_t biWidth;
int32_t biHeight;
int16_t biPlanes;
int16_t biBitCount;
int32_t biComression;
int32_t biSizeImage;
int32_t biXPelsPerMeter;
int32_t biYPelsPerMeter;
int32_t biClrUsed;
int32_t biClrImportant;
} THeader;

#pragma pack(pop)

#include <stdio.h>

int main(void)
{
printf("%lu\n", offsetof(THeader, bfType));
printf("%lu\n", offsetof(THeader, bfSize));
printf("%lu\n", offsetof(THeader, bfReserved1));
printf("%lu\n", offsetof(THeader, bfReserved2));
return 0;
}


$ clang -o pack pack.c
$ ./pack
0
2
6
8