Keywords: lpg

Next: 10.6 Additional Comments Up: 10 Porting Applications to Previous: 10.4.3 Process control under

# 10.5 Portable conditional compilation

If you need to make modifications to existing code in order to port it to Linux, you may need to use `ifdef`...`endif` pairs to surround parts of Linux-specific code--or, for that matter, code corresponding to other implementations. No real standard for selecting portions of code to be compiled based on the operating system exists, but many programs use a convention such as defining `SVR4` for System V code, `BSD` for BSD code, and `linux` for Linux-specific code.

The GNU C library used by Linux allows you to turn on various features of the library by defining various macros at compile time. These are:

- `__STRICT_ANSI__`: For ANSI C features only
- `_POSIX_SOURCE`: For POSIX.1 features
- `_POSIX_C_SOURCE`: If defined as 1, POSIX.1 features; if defined as 2, POSIX.2 features.
- `_BSD_SOURCE`: ANSI, POSIX, and BSD features.
- `_SVID_SOURCE`: ANSI, POSIX, and System V features.
- `_GNU_SOURCE`: ANSI, POSIX, BSD, SVID, and GNU extensions. This is the default if none of the above are defined.

If you define `_BSD_SOURCE` yourself, the additional definition `_FAVOR_BSD` will be defined for the library. This will cause BSD behavior for certain things to be selected over POSIX or SVR4. For example, if `_FAVOR_BSD` is defined, setjmp and longjmp will save and restore the signal mask, and getpgrp will accept a PID argument. Note that you must still link against `libbsd` to get BSD-like behavior for the features mentioned earlier in this paper.

Under Linux, `gcc` defines a number of macros automatically which you can use in your program. These are:

- `__GNUC__` (major GNU C version, e.g., 2)
- `__GNUC_MINOR__` (minor GNU C version, e.g., 5)
- `unix`
- `i386`
- `linux`
- `__unix__`
- `__i386__`
- `__linux__`
- `__unix`
- `__i386`
- `__linux`

Many programs use

      #ifdef linux

to surround Linux-specific code. Using these compile-time macros you can easily adapt existing code to include or exclude changes necessary to port the program to Linux, Note that because Linux supports more System V-like features in general, the best code base to start from with a program written for both System V and BSD is probably the System V version. Alternately, you can start from the BSD base and link against `libbsd`.

Next: 10.6 Additional Comments Up: 10 Porting Applications to Previous: 10.4.3 Process control under