Conditional Compilation

The conditional compilation directives have the effect of determining whether a part of the code should be omitted from the preprocessor stream entirely, based on certain their arguments. For example,

#if !defined NDEBUG

... will cause the code following it until the matching #endif directive to be ignored if the macro value NDEBUG is not previously defined. Since the case of determining if a value is defined or not is particularly common, there are two shortcut versions, #ifdef and #ifndef, which take a macro name; they remove code based on whether the macro is defined or not. The conditional value can be anything, so long as it evaluates to a constant value at compiled time:

#if 2 + 2 == 4

would always remove the code following it. The #elif and #else directives, not surprisingly, can be used to conditionally exclude code for more than one case.

A typical use of conditional compilation is for handling system-specific code for one or more operating systems or platforms; most compilers pre-define appropriate macro values for this purpose. For example:

#ifdef LINUX 
// ... use the Linux code

#elif defined WIN32
// ... use the Windows code

#elif defined (MAC_OS) && defined (OS_X)
// ... use the code for MacOS X

#else 
//  ... use the generic option, if any

#endif
   

Conditional compilation is also often used for debugging:

 foo = bar * quux;

#if SANITY_CHECK

 /* print the value of foo as a sanity check */
 printf("%d", foo);

#endif

In this case, if the macro SANITY_CHECK is set to anything other than 0, the code for the test print is compiled.

Code which is excluded is not processed by the preprocessor for other types of directives.


Contents Previous Next