#include <stdio.h>
enum he {
AGE = 0x01,
NAME = 0x02
};
enum she {
AGE1 = 0x03,
NAME2 = 0x04
};
struct bear {
char x;
char y;
enum he he;
enum she she;
int z;
};
int main(int argc, char **argv)
{
int size = 0;
struct bear bear;
size = sizeof(struct bear);
printf("size is:%d\n", size);
return 0;
}
用gcc test.c时,得出来的结构体的大小为16个字节,两个char型为2个字节,由于第二个char型后面为4个字节的enum型,所以按默认的4个字节对齐,前两个char型为4个字节。再加上两个enum,一个int型,所以总共16个字节。
然而在"#include <stdio.h>"下行加上#pragma pack(1)
编译运行后得到得结构体的大小为14个字节。因为这是按1个字节对齐,两个char型为两个字节,加两个enum,一个int共14个字节。
上面说的是按位对齐,而要把enum变为单个字节,则只需在上面的代码编译时,再加上-fshort-enums参数就行了:
gcc test.c -fshort-enums
运行后得到此结构体的大小只有8个字节了。上面的两个enum型就成就单字节的枚举了。
下面对-fshort-enums在gcc手册中的解释:
-fshort-enums
Allocate to an "enum" type only as many bytes as it needs for the
declared range of possible values. Specifically, the "enum" type will
be equivalent to the smallest integer type which has enough room.
Warning: the -fshort-enums switch causes GCC to generate code that
is not binary compatible with
code generated without that switch. Use it to conform to a
non-default application binary interface.
--
/**************************************/
Name: Xiong Feng
E-mail:linux0818@gmail.com
MSN:linux0818@hotmail.com
QQ:23562033
Address: GuangZhou.China
/**************************************/
没有评论:
发表评论