[LCP]struct size

Robert Wuest rwuest at wuest.org
Sun Aug 19 13:34:48 UTC 2001


Roberto Diaz wrote:
> 
> > I've run into this before. I had a very large struct; handling each item
> > individually was a real pain. Is there any way, with gcc, to force this
> > to pack (ie., somestruct be 6 bytes)?  Some attribute when declaring the
> > struct or a compiler option to prevent word alignment?
> 
> Yes but it is not advisable to pack.. This is a GNU extension and
> non-portable. (why was it a pain to handle its items?)

Because the data was in a serial stream of a bunch (several thousand)
mostly char items.  The data is normally sent between a DOS app (Borland
C) and an embedded 8051 (Keil C) or one of several PICs (Hitech PIC-C)
(and there are some 68HC908's (Cosmic C) thrown in the system for good
measure).  All of those compilers produced packed structs (char
alignment _is_ the natural alignment on an 8 bit processor).

So I had the Borland source, which could directly copy the data to a
struct of chars (and some bitfield unions and some ints, too).  When I
ported to Linux, the struct wasn't lining up, so I had to read the data
into a char[] and copy each item to the struct, one at a time.  Much
largr, harder to maintain and the resulting struct size does not reflect
the datagram size.  It took many "extra" hours to port.  __attribute__
((packed))  would have saved me a bunch of time (and I may go back and
redo it, just for code readability).

Wow, I just searched the gcc info page and there it is:

`packed'
     The `packed' attribute specifies that a variable or structure field
     should have the smallest possible alignment--one byte for a
     variable, and one bit for a field, unless you specify a larger
     value with the `aligned' attribute.

     Here is a structure in which the field `x' is packed, so that it
     immediately follows `a':

          struct foo
          {
            char a;
            int x[2] __attribute__ ((packed));
          };

Now I know I searched for that  before :)

Thanks,

Robert


> 
>  struct S {} __attribute__ ((packed));
> 
> Regards
> 
> Roberto
> 
> ------------------------------------------------------------------------
> Roberto Diaz <rdiazmartin at vivaldi.dhis.org>
> http://vivaldi.dhis.org
> Powered by GNU running on a Linux kernel.
> Powered by Debian (The real wonder)
> 
> Concerto Grosso Op. 3/8 A minor
> Antonio Vivaldi (so... do you need beautiful words?)
> ------------------------------------------------------------------------



More information about the linuxCprogramming mailing list