Mail Archives: djgpp/1996/04/16/00:41:16
Reply to message 3101999 from JES AT PRESTO DOT ME on 04/11/96 5:19PM
>Like everyone else, I wanted to use a structure as a file header, but
>I knew gcc was going to try to align the members. Trying to be smart
>(and trying to avoid explicitly packing the elements), I placed the
>long element first, assuming it wouldn't need extra padding. Gcc
>outsmarted me though, and padded the size of the structure to a
>multiple of four; I suppose to preserve alignment if it were used in
>an array (which it wasn't). So,
>
> read(fd, buf, sizeof(struct header_t))
>
>was reading two bytes too far even though none of the structure
>elements needed padding.
>
>Sigh. Structures as file headers: just say 'no'.
That's not true at all. In addition to being able to pack individual
elements of structures, gcc also allows you to pack the _entire_
structure. Look in the gcc docs for the __attribute__ directive.
To force the compiler to pack the structure to the absolute minimum
size, justdo this:
struct foo
{
long blah;
char c;
short q[3];
#if defined(GNUC)
} __attribute__((packed));
#else
};
#endif
This will make the structure exactly 4+1+6=11 bytes long, where it
would otherwise be (4+0) + (1+3) + (6+2) = 16 bytes.
The #if directives ensure portability by only invoking __attribute__
if you are in fact running a GNU compiler. AFAIK, any compiler
that doesn't allow you to explicitly pack structures should do so
by default (such as Turbo C), so the above will create a completely
portable structure definition.
John
- Raw text -