Jason Freund writes:
> Now I moved to Widows and use CW and  VisualC++, and it seems like you no
> longer need to reverse the bitfields in order to make the data compatible.

You mean with CW and VC++ both targeting Windows?  You might well be lucky
enough.

> the nuances of using bitfields on different platforms [...]

The nuances are very simple:  DO NOT DO THIS!  You have very little
expectation of binary compatibility just moving structures from platform
to platform.  You have ZERO expectation of such binary compatibility when
bit-fields are involved.  A bit-field's effective size and alignment,
whether it may span multiple natural machine words, and the positions and
order in which several bit-fields are placed in a machine word are all
completely undefined.  Hence compilers are free to lay them out in quite
different ways, especially since diffent platforms disagree on what they
think a "natural machine word" is.

Bit-fields are fine when they stay in core and aren't expected to have
any binary compatibility with anything else.  But don't write them to a
file and expect a different machine to be able to read them natively:
instead, the best approach is to have the file contain some kind of encoded
representation of the bit-field's value.  (Like text for example -- there's
a reason why most Internet protocols are text-based!)

If a platform's ABI specifies the layout of bit-fields, then you'd expect
to be all right as long as you limited yourself to that platform.  But not
all platforms define that layout.  For example (to make this relevant to
palm-dev-forum)...

Palm OS doesn't fully specify the layout of bit-fields.  The two major
compilers for Palm OS, CodeWarrior and GCC, do not always lay out bit-fields
the same way.  If a group of contiguous bit-fields has a total width which
is not a multiple of 16, then CW will allocate them in the high bits of
a 16 bit word, while GCC puts them at the low end.  Or vice versa.  Or
something.

Library API designers take note!  If you have a function taking a struct
with bit-fields in it, you need to make sure that the bit-fields total to a
multiple of 16, or else users of one of the compilers won't be able to use
your library.  (Fortunately you can fix your headers later without breaking
anything.  The Palm OS headers are almost right -- there's just a couple
still lurking.)

    John   "dammit, Keith beat me to it :-)"

Reply via email to