struct - alignment

Robert Vojta vojta na ipex.cz
Pondělí Červen 25 09:57:05 CEST 2001


> mohl by mi nekdo napsat, jak donutim GCC, aby mi prvky ve strukturach
> ukladalo v pameti hned za sebe a nedelalo mezery? Zatim to mam tak, ze
> kdyz man ve strkture za sebou char[3] a int, tak ze to mezi nimi udela
> mezeru a ten int ulozi az na sudou adresu. Da se to udelat bez te
> mezery?
> 
> Kdyz jsem delal v Metaware HighC, bylo na to pragma Align_members(1). Je
> neco takoveho v gcc? Zkousel jsem #pragma align 1, ale zacalo to psat
> nesmyslne chybove hlasky.

...<lkml>...
You're expecting the compiler to lay them out without any spacing between
them.  There is no such requirement in C.

The compiler knows that its more efficient for long words to be accessed
on a long word boundary, so it wastes two bytes after each short in your
bad_struct case.  However, it won't waste them in this case, because there
isn't a long:

struct { short x; short y; short z; }

If you really really really want that layout, then use
__attribute__((packed)) (read the gcc info files to find out what this
does), but don't unless you absolutely must.

Here is another struct layout example:

struct foo {
        short x;
        char y;         /* implicit 1 byte padding after this element */
        short z;                                                        
};

Again, the 1 byte padding can be removed by use of the __attribute__
above.
...</lkml>...

Best,
  Robert

-- 
   _
  |-|  __      Robert Vojta <vojta-at-ipex.cz>          -= Oo.oO =-
  |=| [Ll]     IPEX, s.r.o.
  "^" ====`o
------------- další část ---------------
A non-text attachment was scrubbed...
Name: [žádný popis není k dispozici]
Type: application/pgp-signature
Size: 240 bytes
Desc: [žádný popis není k dispozici]
URL: <http://www.linux.cz/pipermail/linux/attachments/20010625/41a609c3/attachment.sig>


Další informace o konferenci Linux