The preprocessor allows code to be compiled
selectively, depending on some condition. For example, if
we assume that the macro __unix__
is defined only when compiling
for a UNIX system, and that the macro __windows__
is defined only when
compiling for a Windows system, then we could provide a
single piece of code containing two possible
implementations depending on the intended target:
int file_exists(const char *name) { #if defined __unix__ /* Use UNIX system calls to find out if the file exists. */ . . . #elif defined __windows__ /* Use Windows system calls to find out if the file exists. */ . . . #else /* Don't know what to do - abort compilation. */ #error "No implementation for your platform." #endif }
The most common use of conditional compilation,
though, is to prevent the declarations in a header file
from being made more than once, should the file be
inadvertently #include
d more than
once:
/* in the file mydecls.h */ #if !defined(mydecls_header) #define mydecls_header typedef int myInteger; #endif
You should routinely protect all your header files in this way.