分类: LINUX
2013-09-03 16:37:24
__attribute__
, the syntax of which is __attribute__((attribute list))
. One such attribute is __packed__
which specifies that
a variable or structure field should have the smallest possible alignment--one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute.which means that GCC will not add any of the zero's for padding (for memory alignement) and make variables or fields immediately next to each other. For example, here are some things I tried out -- I created a C source file - test.c
struct test_t {And compiled it with the -S option (ie to generate the assembly equivalent of the code generated).
int a;
char b;
int c;
} ;
struct test_t test = { 10, 20, 30};
$gcc -c test.c -S -o test.sThe file test.s -
.file "test.c"Notice the emphasized code. You can see that the structure "test" is being declared. First the field "a" (int) as
.globl test
.data
.p2align 2
.type test,@object
.size test,12
test:
.long 10
.byte 20
.zero 3
.long 30
.ident "GCC: (GNU) 3.2.2 [FreeBSD] 20030205 (release)"
.long 10
followed by "b" (char) as .byte 20
. To keep the fields' word alignment, notice that GCC has added 3 zero bytes (.zero 3
) before field "c" (int) which is declared as .long 30
. This makes the effective sizeof struct test_t as 12 instead of the expected 9. Then I tried with the __packed__
attribute -
struct test_t {and the "-S" output I got after compiling was
int a;
char b;
int c;
} __attribute__((__packed__));
struct test_t test = { 10, 20, 30};
.file "test.c"in which the zeros are missing making the sizeof structure test_t = 9.
.globl test
.data
.type test,@object
.size test,9
test:
.long 10
.byte 20
.long 30
.ident "GCC: (GNU) 3.2.2 [FreeBSD] 20030205 (release)"
|
sizeof s1 is 8
sizeof s2 is 5
-
-