instructing gcc for alignment

Megatron Eye megatroneye@gmail.com
Tue Jul 9 13:57:00 GMT 2013


Well, there is some progress:

1) "pragma pack" started having effect as I separated the typedef from
the type declaration;
2) My expectations (see my previous mail) got fulfilled when I
replaced the "unsigned int" declarations of the two first bitfields in
the struct for "uint8_t".

Still I wonder why would two "unsigned int" bitfields translate into 4
bytes in a 64-bit system but into 1 byte in a 32-bit system.

> >
> > I seem not to be able to properly instruct gcc for producing struct
> > bytes aligned the way I expect.
> > I am using gcc 4.7.0, from the mingw32-64 distribution under Windows
> > 7. My machine is a little-endian x86_64.
> >
> > First let me state my expectations.
> >
> > I have a memory region with these physical contents:
> >
> > 450002cf9fe5000040115a9fc0a8fe...
> >
> > And I have a pointer to the struct defined below initialized to the
> > beginning of that region (the byte with contents "45" above).
> >
> > typedef struct ip4 {
> >   unsigned int ihl :4;
> >   unsigned int version :4;
> >   uint8_t tos;
> >   uint16_t tot_len;
> >   uint16_t id;
> >   uint16_t frag_off; // flags=3 bits, offset=13 bits
> >   uint8_t ttl;
> >   uint8_t protocol;
> >   uint16_t check;
> >   uint32_t saddr;
> >   uint32_t daddr;
> >   /*The options start here. */
> > } ip4_t;
> >
> > Now, gdb shows the following situation in runtime:
> >
> > ip4:                   address=0x8da36ce
> > ip4->ihl:              address=0x8da36ce, value=0x5
> > ip4->version:          address=0x8da36ce, value=0x4
> > ip4->tos:              address=0x8da36d2, value=0x9f
> > ip4->tot_len:          address=0x8da36d4, value=0x0
> >
> > But my expectations (basing on how the 32-bit-compiled version of this
> > code behaves) are:
> >
> > ip4->tos:              address=0x8da36cf, value=0x0
> > ip4->tot_len:          address=0x8da36d0, value=0x02cf.
> >
> > It seems gcc aligns the ihl and version bitfields to a 4-byte
> > boundary. That causes subsequent fields to be wrongly mapped. My goal
> > is to configure the padding/aligment so that the physical size of the
> > structure will be in agreement with the logical size.
> >
> > I have tried the following options:
> >
> > * -fpack-struct
> > * The aligned attribute
> > * The packed attribute
> > * The pragma pack (1)
> > * Combinations of the above
> >
> > With no visible effects so far.
> >
> > I will appreciate any hints on this issue.
> >
> > Best regards,
> >
> > D.
>



More information about the Gcc-help mailing list