Keil Logo

Conditional Compilation

Conditional compilation directives allow you to designate parts of the program for the compiler to ignore. These parts are not compiled and no object code is generated for them.

Conditional directives resemble the C if statement and may be used to test defined macros or arithmetic expressions. The test performed by a conditional directive is done at compile-time by the compiler. Depending on the result of the test, source code is either included or excluded from the compilation.

There are several reasons to use conditional compilation in your program.

  • Your program may require different code depending on which device or architecture you use. In some cases, library routines may exist in one configuration that do not exist in another. Conditional compilation allows you to handle such a situation by substituting alternate functions with the unavailable library routines.
  • Many complex functions require comprehensive test code to verify or validate I/O and proper operation. Intermediate values may be tested and output as well. After verification, you may wish to retain the test cases for future reference. You can include them in conditional blocks you control with a macro. For example:
    #define DEBUG 0

    The following test case compiles only when DEBUG is defined to a value other than 0.

    #if DEBUG   /*** Test Case ***/
  • Often, it is necessary to replace or rewrite certain sections of a working program. Conditionals allow you to retain old code in the source file by placing it in a conditional block. For example:
    #if 0   /*** Old code from 1999 ***/

Following is a list of the available conditional compilation directives.

Directive Description
#elif Initiates an alternative branch of the if condition, when the previous #if, #ifdef, #ifndef, or #elif branch was not taken.
#else Initiates an alternative branch when the previous #if, #ifdef, or #ifndef branch was not taken.
#endif Ends a #if, #ifdef, #ifndef, #elif, or #else block.
#ifdef Evaluates an expression for conditional compilation. The argument to be evaluated is the name of a definition.
#ifndef Same as #ifdef but the evaluation succeeds if the definition is not defined.
#if Evaluates an expression for conditional compilation.
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.