#include <stdio.h>
#define ATTRIBUTE
#ifdef ATTRIBUTE
#define ATTR __attribute__ /*((aligned(8)))*/((packed))
#else
#define ATTR
#endif
typedef struct ATTR _size
{
char name[7];
int b;
}size;
int main()
{
printf("sizeof int = %d\nsizeof struct size = %d\n", sizeof(int), sizeof(size));
}
1.
在TC下:struct my{ char ch; int a;}sizeof(int)=2;sizeof(my)=3;(紧凑模式)
在GCC下:struct my{ char ch; int a;}sizeof(int)=4;sizeof(my)=8;(非紧凑模式)
在GCC下:struct my{ char ch; inta;}__attrubte__ ((packed))
2.__attribute__关键字主要是用来在函数或数据声明中设置其属性。给函数赋给属性的主要目的在于让编译器进行优化。函数声明中的__attribute__((noreturn)),就是告诉编译器这个函数不会返回给调用者,以便编译器在优化时去掉不必要的函数返回代码。
GNU C的一大特色就是__attribute__机制。__attribute__可以 设置函数属性(FunctionAttribute)、变量属性(Variable Attribute)和类型属性(Type Attribute)。__attribute__书写特征是:__attribute__前后都有两个下划线,并且后面会紧跟一对括弧,括弧里面是相应的__attribute__参数。
__attribute__语法格式为:
__attribute__ ((attribute-list))
其位置约束:放于声明的尾部“;”之前。
函数属性(Function Attribute):函数属性可以 帮助 开发者把一些特性添加到函数声明中,从而可以使编译器在错误检查方面的功能更强大。__attribute__机制也很容易同非GNU 应用 程序做到兼容之功效。
GNU CC需要使用–Wall编译器来击活该功能,这是控制警告信息的一个很好的方式。
GNUC的一大特色(却不被初学者所知)就是__attribute__机制。__attribute__可以设置函数属性(FunctionAttribute)、变量属性(VariableAttribute)和类型属性(TypeAttribute)。
__attribute__语法格式为:
__attribute__ ((attribute-list))
其位置约束为:放于声明的尾部“;”之前。
packed是类型属性(TypeAttribute)的一个参数,使用packed可以减小对象占用的空间。需要注意的是,attribute属性的效力与你的连接器也有关,如果你的连接器最大只支持16字节对齐,那么你此时定义32字节对齐也是无济于事的。
使用该属性对struct或者union类型进行定义,设定其类型的每一个变量的内存约束。当用在enum类型定义时,暗示了应该使用最小完整的类型(itindicates that the smallest integral type should beused)。
下面的例子中,my-packed-struct类型的变量数组中的值会紧凑在一起,但内部的成员变量s不会被“pack”,如果希望内部的成员变量也被packed的话,my-unpacked-struct也需要使用packed进行相应的约束。
struct my_unpacked_struct
{
};
struct my_packed_struct
{
}__attribute__ ((__packed__));
struct student
{
} __attribute__((aligned(4)));
2)不对齐,结构体的长度,就是各个变量长度的和
struct student
{
} __attribute__ ((packed));