首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

linux 与windows地址对齐有关问题

2012-09-13 
linux 与windows地址对齐问题结构体typedef struct {__u8 a1:4__u8 a2:1__u16 a3:11__u16 a4__u16 a5

linux 与windows地址对齐问题
结构体

typedef struct {
__u8 a1:4;
__u8 a2:1;
__u16 a3:11;
__u16 a4; 
__u16 a5;
}mystr;


在linux下sizeof(mystr)结果是6字节

windows下sizeof(mystr)结果是8字节

编译器的对齐方式造成的吗?

有没有不进行优化的对齐方式呢?也就是在windows下sizeof(mystr)结果也是6字节?

各位大侠请赐教。

[解决办法]
#pragma pack( [ n] )

Specifies packing alignment for structure and union members. Whereas the packing alignment of structures and unions is set for an entire translation unit by the /Zp option, the packing alignment is set at the data-declaration level by the pack pragma. The pragma takes effect at the first structure or union declaration after the pragma is seen; the pragma has no effect on definitions.

When you use #pragma pack(n), where n is 1, 2, 4, 8, or 16, each structure member after the first is stored on the smaller member type or n-byte boundaries. If you use #pragma pack without an argument, structure members are packed to the value specified by /Zp. The default /Zp packing size is /Zp8.

[解决办法]
你的第二个问题,我想用 #pragma pack(1)可以办到 //等会儿代码测试下才能确认

第一个问题,我觉得你可以自己 写一个位移宏,验证关心的元素的位移,就知道是否填充,进而知道原因了
#define OFFSET(A,a) &(((A)*)(void * )0 ->(a) ) //A是结构体名称,a是结构体成员
[解决办法]
不知道是编译器还是操作系统的原因,反正在linux下所有位域加起来不足1byte的补足1byte ,大于1byte小于2byte的补足2byte。。。

windows下看结果好像是对每个位域都采取了linux下的措施。
[解决办法]
http://blog.csdn.net/wshn13/article/details/7835155
[解决办法]
你可以设置结构体的对齐方式,在windows下,结构体对齐的方式是按结构体中成员变量最大的对齐,没有最高限制;在linux下,结构体对齐的方式是按结构体中成员变量最大的对齐,结构体对齐的最高位4个字节。
[解决办法]
只能说gcc强大,尽管类型不同,但是还是把前3个合为一体用2字节存储,这跟字节对齐没关系
想一样的话大概把
__u8 a1:4;
__u8 a2:1;
都修改为u16应该就可以了

[解决办法]
printf("%u\n", sizeof(int)); // 检查下你的系统

热点排行