[lug] OFF: sizeof structs in gcc?
Tkil
tkil at scrye.com
Thu Jun 7 14:03:39 MDT 2001
>>>>> "Scott" == Scott A Herod <herod at interact-tv.com> writes:
Scott> Is it true that gcc allocates space for objects/stucts in 4
Scott> byte words?
it usually prefers the fastest allocation for the given platform,
which is usually at least 4 bytes (e.g. doubles might be faster on
8-byte boundaries)
Scott> Is there a way to avoid this?
you want to look at the "packed" attribute. from:
info '(gcc.info)Type Attributes'
we have:
| `packed'
| This attribute, attached to an `enum', `struct', or `union'
| type definition, specified that the minimum required memory be
| used to represent the type.
|
| Specifying this attribute for `struct' and `union' types is
| equivalent to specifying the `packed' attribute on each of the
| structure or union members. Specifying the `-fshort-enums'
| flag on the line is equivalent to specifying the `packed'
| attribute on all `enum' definitions.
|
| You may only specify this attribute after a closing curly brace
| on an `enum' definition, not in a `typedef' declaration, unless
| that declaration also contains the definition of the `enum'.
so, you might do:
| #include <stdio.h>
| #include <stddef.h> /* for offsetof() macro */
|
| struct unpacked_struct { short a; long b; };
| struct packed_struct { short a; long b; } __attribute__ ((packed));
|
| int main(int argc, char * argv [])
| {
| printf("unpacked: sizeof=%d, offset(a)=%d, offset(b)=%d\n",
| sizeof (struct unpacked_struct),
| offsetof(struct unpacked_struct, a),
| offsetof(struct unpacked_struct, b) );
| printf("packed: sizeof=%d, offset(a)=%d, offset(b)=%d\n",
| sizeof (struct packed_struct),
| offsetof(struct packed_struct, a),
| offsetof(struct packed_struct, b) );
| return 0;
| }
which, on kevin's athlon, yields:
| $ ./pack
| unpacked: sizeof=8, offset(a)=0, offset(b)=4
| packed: sizeof=6, offset(a)=0, offset(b)=2
t.
More information about the LUG
mailing list