Re: ISO: help porting C code to 64 bit linux platform

Emmanuel Fleury <emmanuel.fleury@xxxxxxxx> writes:

Måns Rullgård wrote:

That is a good example of how *not* to write code. *Never*, ever read
or write a struct directly to/from a file. The compiler is free to
insert padding wherever it likes in a struct.

Somehow, I feel you are both right... but you didn't set properly your
initial conditions.

I think that this is true to FORCE variables size when the data are
coming from outside the program. Typically, in the example of Julián the
struct describe the structure of a wav file which should be played on
any type of machine. This is clearly some data imported from outside the
software and on which the programmer has no control.

The WAV header has a number of fixed-size fields, that is true.
However, that does not imply that the variables used to hold these
values inside a program need to have the same size. They need to be
at least as wide, but it doesn't hurt if they are wider if that makes
for more efficient code.

The correct way to handle things like a WAV header is to read one
value at a time, convert it to the machine endianness (the WAV header
is always little endiean). Reading the header directly into a struct
can lead to unpleasant surprises if the compiler inserted padding you
didn't expect, and you still need to handle endian conversions.

On the other hand, Måns is right for all the variables which are lying
within the program. It should be define as a coherent data flow without
relying on the size of it.

At last, variables which are exported outside of the software must also
have a known size ('cause they will be imported at some other point).

Any data going into or out of a program must of course have a defined
format. Now this format need only exist at the external interface.
In most situations it is preferable to immediately convert input into
some more efficient internal format, and convert back on output.

Måns Rullgård