您的位置:首页 > 其它

使用gcc中的__attribute__指定字节对齐

2017-12-14 12:10 323 查看
在x86(32位机器)平台下,GCC编译器默认按4字节对齐:

如:结构体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 对齐。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: