使用gcc中的__attribute__指定字节对齐
2017-12-14 12:10
323 查看
在x86(32位机器)平台下,GCC编译器默认按4字节对齐:
如:结构体4字节对齐,即结构体成员变量所在的内存地址是4的整数倍。
② attribute((aligned (n))),让所作用的结构体成员对齐在n字节边界上。如果结构体中有成员变量的字节长度大于n,则按照最大成员变量的字节长度来对齐。
结果:
作用:确保n是以x字节对齐
例如:
-》
作用:确保n是以4字节对齐
解释:+3, 是保证比这个数4大;&~3,是保证后两位bit 为0,即被4整除。所以合起来:比s 大的能被4整除的数, 通俗讲就是按4byte 对齐。
如:结构体4字节对齐,即结构体成员变量所在的内存地址是4的整数倍。
可以通过使用gcc中的_attribute_选项来设置指定的对齐大小
① attribute((packed)),让所作用的结构体取消在编译过程中的优化对齐,按照实际占用字节数进行对齐② attribute((aligned (n))),让所作用的结构体成员对齐在n字节边界上。如果结构体中有成员变量的字节长度大于n,则按照最大成员变量的字节长度来对齐。
#include <stdio.h> struct person0{ char *name; int age; char score; int id; }; struct person1{ char *name; int age; char score; int id; }__attribute__((packed)); struct person2{ char *name; int age; char score; int id; } __attribute__((aligned (4))); int main(int argc,char **argv) { printf("size of (struct person0) = %d.\n",sizeof(struct person0)); printf("size of (struct person1) = %d.\n",sizeof(struct person1)); printf("size of (struct person2) = %d.\n",sizeof(struct person2)); return 0; }
结果:
补充:
#define CZG_SIZE(n) ((n + (x-1)) & ~(x-1))
作用:确保n是以x字节对齐
例如:
#define CZG_SIZE(n) ((n + (3)) & ~(3))
-》
#define CZG_SIZE(n) ((n + (4-1)) & ~(4-1))
作用:确保n是以4字节对齐
解释:+3, 是保证比这个数4大;&~3,是保证后两位bit 为0,即被4整除。所以合起来:比s 大的能被4整除的数, 通俗讲就是按4byte 对齐。
相关文章推荐
- GCC___attribute__关键字和字节对齐
- GCC___attribute__关键字和字节对齐
- 使用__attribute__处理对齐问题
- TGA图像头文件拾取的字节对齐及#pragma pack的使用
- chrome 中在栈上创建指定字节对齐的POD类型的static数据的一种可移植的方法
- C# 使用 StructLayoutAttribute 时 C# /C++ 内存空间分配与成员对齐问题
- 静态链接,一字节对齐时CGridCtrl使用出错
- 结构体(struct)的使用、内存分布以及字节对齐测试总结
- 属性(Attribute)资源使用自定义组件,并指定属性资源中定义的属性
- C语言的字节对齐及#pragma pack的使用
- 结构体字节对齐和位域对齐——VC、gcc
- vc下和gcc的结构体紧凑对齐格式存储【#pragma pack(push,1)、__attribute__ ((packed, aligned(1)))】
- GCC 4.7+ version 字节对齐
- Linux下的 arm-linux-gcc 与 gcc 关于字节对齐问题
- VC和gcc下的结构体字节对齐和位域对齐
- gcc下__attribute__ ((constructor))和__attribute__ ((destructor))的使用
- gcc 函数属性 __attribute__ ((constructor))使用
- GCC 字节对齐设置
- gcc 中的"__attribute__ ((packed))" gcc移植,内存对齐.结构体对齐-转
- 【转】attribute与字节对齐