gcc - How to override C compiler aligning word-sized variable in struct to word boundary -


i have structure specified following

  • member 1, 16 bits
  • member 2, 32 bits
  • member 3, 32 bits

which shall reading file. want read straight file struct.

the problem c compiler align variables m1, m2 , m3 word boundaries @ 32 bits since working on arm cortex m3 following struct declaration:

typedef struct {     uint16_t m1;     uint32_t m2;     uint32_t m3; }something; 

reading directly file put wrong values in m2 , m3, , reads 2 bytes too.

i have hacked around , using following works fine:

typedef struct {     uint16_t m1;     struct     {         uint16_t lo;         uint16_t hi;     }m2;     struct     {         uint16_t lo;         uint16_t hi;     }m3; }something; 

however, looks dirty hack. cannot wishing cleaner way force compiler put halves of m2 , m3 in different words, sub-optimal may be.

i using arm-none-eabi-gcc. know bit packing, unable work around optimisation.

edit: turns out didn't know enough bit-packing :d

what looking packed attribute. force gcc not padding around members. taken gcc online docs:

packed

this attribute, attached enum, struct, or union type definition, specified minimum required memory used represent type. specifying attribute struct , union types equivalent specifying packed attribute on each of structure or union members. specifying -fshort-enums flag on line equivalent specifying packed attribute on enum definitions.

you may specify attribute after closing curly brace on enum definition, not in typedef declaration, unless declaration contains definition of enum.

so want like:

typedef struct {     uint16_t m1;     uint32_t m2;     uint32_t m3; } __attribute__ ((packed)) something; 

in addition recommend using compile time assertion check ensure size of struct want be.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -