
writing portable C (DOS to UNIX) -- suggestions?
Quote:
>>I'd like to anticipate any problems that could arise when porting [C]
>>to UNIX.
[... A lot of good, sound advice truncated for brevity...]
Quote:
>If you choose ANSI C, get a
>copy of the standard (you can get it for about $50 from ANSI in New
The FAQ says it costs four times this. :-)
Quote:
>Use the standard as your reference manual (it's pretty easy
>to understand) rather than your compiler's library reference manual.
As a reference manual, yes, the ANSI standard is the final word.
But to learn portable programming, it is IMO better to go through the ANSI
rationale. It is available via anonymous ftp (I forgot the site).
[...]
Quote:
> - Don't use the comma operator to join expressions of unlike type.
You mean as a matter of style? Then I won't argue. But syntactically
and semantically, there is nothing wrong in using the comma operator to join
expressions of unlike type. Are there any non-conforming compilers which
make a comma expression return a type different from the type of the last
expression?
Quote:
> - Don't use bit fields. Bit fields are, in general,
> non-portable (not because they're inherently that way, but
> because many compilers have gotten this wrong -- this may not
> be that big a deal since the ANSI standard and compliance
> issues have come into the compiler business).
Bit fields _are inherently non-portable_. The order of assignment of
the bits are implementation-defined (even in the ANSI standard). The spacing
between consecutive bit fields is implementation defined (actually, the ANSI
standard says that the bit fields should be packed together if they fit into a
storage unit, but the type of the storage unit itself is
implementation-defined).
Some other issues of portability that have come up on the net:
There are a lot of reserved (or quasi-reserved) identifiers in
ANSI C. Section 7.13 (ISO version) gives a good list. Also avoid all
identifiers beginning with an '_'.
Be careful with variable arguments (use stdarg.h). Don't treat a
va_list object as a char**, or in fact, as anything other than as a parameter
to a function call, or with the va_... macros.
Do declare main() as int main(void) or as int main(int argc,
char **argv) or as something similar; don't go for void main(void) to shut off
warnings.
For the sake of so-called efficiency, don't assume non-portable
things such as the number of bits in a char (the only guarantee available is
that it is greater than or equal to 8).
Do not assume that all implementations would provide some compiler
flag to turn off structure padding. Lots of networking code typically declare
protocol headers as structures. As long as structure padding can be turned
off, this works, else it fails.
There should be plenty more to add to this do's and dont's list.
------
/* I prefer silver speech to golden silence. */
/* Ajoy Krishnan T,
Software Engineer, Hughes Software Systems,
New Delhi - 19, India.