UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

14.11.3.  The #ifdef, #else and #endif directives

In Section 14.11.2 we have seen that the preprocessor maintains a set of defined symbols, and some of them with their equivalent values. The preprocessor also offers a mechanism by which a portion of the code in a program can be hidden or considered depending on the value of some of the symbols defined with the #define directive. The structure of this construction is the following:

#ifdef SYMBOL
  /* Code block 1 */
  ...
#else
  /* Code block 2 */
#endif

When the preprocessor finds the first directive #ifdef SYMBOL, if SYMBOL is defined, the code block 1 is passed to the compiler (until the #else directive) and the code block 2 is removed (between the #else and #endif directives). Analogously, if SYMBOL is not defined, the code block 1 is removed and the compiler only receives the code block 2. This construction is similar to the typical if/then/else construction in C, but the difference is that this one is interpreted by the preprocessor at compile time. The difference is that if the ignore code block contains a syntax error, the program will be generated normally because that portion of code is never seen by the compiler.

This directive is used when two versions of a program that differ in a reduced number of lines need to be maintained. The two versions may coexist in the same source code but surrounded with this directive. At compile time, the -Dname=value option is used to select the appropriate code blocks and generate the executable.

The following example shows the use of this directive to write to versions of a welcome message to a system with two possible versions. If the MAEMO symbol is defined (for example when compiling with gcc -DMAEMO ...) the first message is printed on execution, and if the symbol is not defined, an alternative message is printed.

#ifdef MAEMO
    printf("Welcome to the Maemo System\n"); /* Code for the MAEMO version */
#else
    printf("Welcome to the other system\n"); /* Code for the other version */
#endif