欢迎来到天天文库
浏览记录
ID:9401214
大小:10.43 KB
页数:3页
时间:2018-04-30
《字节对齐问题gcc编译器对齐字节修改》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、嵌入式开发要编的第四个程序:字节对齐问题示例程序一:#includestructst1{intx;shorty;charz;};structst2{shorty;intx;charz;};intmain(intargc,char*argv[]){printf("sizeof(structst1)=%d",sizeof(structst1));printf("sizeof(structst2)=%d",sizeof(structst2));return0;}//默认的是4字节对齐//输出结果
2、://sizeof(structst1)=8//sizeof(structst1)=12程序解释什么是字节对齐?为了使CPU能够对变量进行快速的访问,变量的起始地址应该具有某些特性,即所谓的”对齐”.比如在32位系统下的的int型变量占4个字节,在分配内存时其起始地址应该位于4字节的边界上,即起始地址能够被4整除。示例程序二:#pragmapack(1)structst1{intx;shorty;charz;};structst2{shorty;intx;charz;};#pragmapack()intmain(i
3、ntargc,char*argv[]){structst1s1;structst2s2;printf("sizeof(structst1)=%d",sizeof(structst1));printf("sizeof(structst2)=%d",sizeof(structst2));printf("st1s1Addr0x%x",&s1);printf("st1s1.xAddr0x%xxint",&s1.x);printf("st1s1.yAddr0x%xyshort",&s1.y);prin
4、tf("st1s1.zAddr0x%xzchar",&s1.z);printf("st1s2Addr0x%x",&s2);printf("st1s2.yAddr0x%xyshort",&s2.y);printf("st1s2.xAddr0x%xxint",&s2.x);printf("st1s2.zAddr0x%xzchar",&s2.z);return0;}//pragmapack(1)设置1字节对齐//输出结果//sizeof(structst1)=7//sizeof(structst2
5、)=7//st1s1Addr0xbfbaa0dd//st1s1.xAddr0xbfbaa0ddxint//st1s1.yAddr0xbfbaa0e1yshort//st1s1.zAddr0xbfbaa0e3zchar//st1s2Addr0xbfbaa0d6//st1s2.yAddr0xbfbaa0d6yshort//st1s2.xAddr0xbfbaa0d8xint//st1s2.zAddr0xbfbaa0dczchar程序解释修改默认字节对齐但是如果采用使用1字节或者2字节对齐,会降低变量访问速度降低。GNUg
6、cc编辑器默认4字节对齐。如果确实需要,可以通过下面的方法来改变缺省的对界条件:·使用伪指令#pragmapack(n),C编译器将按照n个字节对齐。·使用伪指令#pragmapack(),取消自定义字节对齐方式。所以,我们需要在时间(速度)和空间之间进行取舍,如果取消默认的4字节对齐,那么CPU在访问变量寻址的时候会花去大量的时间去找某些变量在内存中存在那了?如果就使用4字节对齐的方式,我们或多或少要浪费一些内存空间。
此文档下载收益归作者所有