EmbDev.net

Forum: ARM programming with GCC/GNU tools Packing structures on bit boundaries


von Charles Z. (geodesic)


Rate this post
useful
not useful
I have a an issue with gcc and I am looking for help.

I am trying to use a library that was designed for a different 
environment on a RAM constrained cortex-M0 processor. The library itself 
makes extensive use of structures like the following (details removed to 
express the problem succinctly):

struct {
   struct {
      int chan1;
      int chan2;
   } dma;
   int state;
} X;

By default, this takes up 12 bytes. But the range of possible values for 
these fields are very small. I would like to change it to the following:

struct __attribute__(( packed )) {
   struct __attribute__(( packed )) {
      uint8_t chan1:2;
      uint8_t chan2:2;
   } dma;
   uint8_t  :1;
   uint8_t  state:3;
} X;

This structure should only take 1 byte. But it seems gcc is always 
padding out the dma structure to a full byte, and then placing the state 
field in a second byte. So my structure winds up with size 2. I have 
read everything on the net and have not yet found anything which would 
allow me to tell gcc not to pad the dma structure, or to align it on a 
nibble boundary.

I am stuck with this structure. To change it would require changing it 
in hundreds of places of C code, and worse, redoing it every single time 
there was a library code update.

This is doubling my RAM usage. If I could find a way to make gcc behave, 
then we could squeeze into a smaller part.

Does anyone have any idea on a way to make the gcc compiler be more 
accommodating to my constraints?

Thank you for any assistance.

von Rolf Magnus (Guest)


Rate this post
useful
not useful
Charles Zi wrote:
> This structure should only take 1 byte. But it seems gcc is always
> padding out the dma structure to a full byte, and then placing the state
> field in a second byte.

Yes, because it's a separate type. The dma struct is one bit field that 
must have a size that is a multiple of one byte. That doesn't change 
just because it is embedded into another structure with bitfield 
elements.

> I have read everything on the net and have not yet found anything which
> would allow me to tell gcc not to pad the dma structure, or to align it
> on a nibble boundary.

I don't think there a way to put bits of multiple bit fields together 
into one byte.

> I am stuck with this structure. To change it would require changing it
> in hundreds of places of C code,

Then better start now ;-)

> and worse, redoing it every single time there was a library code update.

Why?

Please log in before posting. Registration is free and takes only a minute.
Existing account
Do you have a Google/GoogleMail account? No registration required!
Log in with Google account
No account? Register here.