HP C Programmer's Guide (92434-90009)

122 Chapter5
Programming for Portability
Guidelines for Portability
Guidelines for Portability
This section lists some things you can do to make your HP C programs more portable.
Use the ANSI C compiler option whenever possible when writing new programs. HP C
conforms to the standard when it is invoked with the -Aa option. The -w and +e options
should not be used with the -Aa option, as these options will suppress warning
messages and allow non-conforming extensions.
When you recompile existing programs, try compiling in ANSI mode. ANSI C mandates
more thorough error checking, so portability problems are more likely to be flagged by
the compiler in this mode. (Bugs are also more likely to be caught.) Many existing
programs will compile and execute correctly in ANSI mode with few or no changes.
Pay attention to all warnings produced by the compiler. Most warnings represent
potentially problematic program constructs. You should consider warnings to be
portability risks.
For an additional level of warnings, compile with the +w1 option. Pay particular
attention to the warnings that mention "ANSI migration" issues. These identify most
program constructs that are legal but are likely to work differently between pre-ANSI
and ANSI compilers.
Consult the detailed listing of diagnostic messages in the HP C Reference Manual for
more information on how to correct each problem. For most messages, a reference to the
relevant section of the ANSI standard is also given.
On HP-UX, use lint, the C program syntax checker, to detect potential portability
problems in your program. The lint utility also produces warnings about poor style,
lack of efficiency, and inconsistency within the program.
Use the #define, #if, and #ifdef preprocessing directives and typedef declarations
to isolate any necessary machine or operating system dependencies.
Declare all variables with the correct types. For example, functions and parameters
default to int. On many implementations, pointers and integers are the same size, and
the defaults work correctly. However, for maximum portability, the correct types should
be used.
Use only the standard C library functions.
Code bit manipulation algorithms carefully to gain independence from machine-specific
representations of numeric values. For example, use x&~3instead of x & 0xFFFFFFFC
to mask the low-order 2 bits to zero.
Avoid absolute addressing.
Examples
The following example illustrates some ways to program for portability. In this example,
the include files IEEE.h and floatX.h isolate machine-dependent portions of the code.
These include files use the #define and typedef mechanisms to define macro constants
and type definitions in the main body of the program.