Skip to content

c - PORTABILITY AND PERFORMANCE #19

@nixawk

Description

@nixawk

Code is often developed on one type of computer and then
ported to and executed on another. Therefore, it is judicious to
make the code as portable as possible, requiring no changes or
minimal ones—such as changes to system-specific header files.
When writing software, consider the following guidelines that
will enhance portability and performance.

Guidelines for Portability

  • Use ANSI C whenever it is available.

  • Write portable code first. Consider detailed optimizations only on computers
    where they prove necessary. Optimized code is often obscure.
    Optimizations for one computer may produce worse code on another.
    Document code that is obscure due to performance optimizations and isolate
    the optimizations as much as possible.

  • Some code/functions are inherently nonportable. For example, a hardware
    device handler, in general, can not be transported between operating systems.

  • If possible, organize source files so that the computer-independent code and
    the computer-dependent code are in separate files. That way, if the program
    is moved to a new computer, it will be clear which files need to be changed for
    the new platform.

  • Different computers have different word sizes. If you are relying on a
    (predefined) type being a certain size (e.g., int being exactly 32 bits), then
    create a new type (e.g., typedef long int32) and use it (int32) throughout the
    program; further changes will require only changing the new type definition.

  • Note that pointers and integers are not necessarily the same size; nor are all
    pointers the same size. Use the system function sizeof(...) to get the size of a
    variable type instead of hard-coding it.

  • Beware of code that takes advantage of two’s complement arithmetic. In
    particular, avoid optimizations that replace division or multiplication with
    shifts.

  • Become familiar with the standard library and use it for string and character
    manipulation. Do not reimplement standard routines. Another person reading
    your code might see the reimplementation of a standard function and would
    need to establish if your version does something special.

  • Use #ifdefs to conceal nonportable quirks by means of centrally placed
    definitions.

Example: centrally placed definitions

#ifdef decus
#define UNSIGNED_LONG long
#else
#define UNSIGNED_LONG unsigned long
#endif

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions