Conditional Compilation - C Preprocessor

C examples for Preprocessor:Preprocessor Operators

Introduction

The directives for conditional compilation can include or exclude part of the source code for a certain condition.

#if and #endif directives includes a section of code if the condition after the #if directive is true.

#define DEBUG_LEVEL 3

#if DEBUG_LEVEL > 2
 /* ... */
#endif

Any number of #elif (else if) directives and one final #else directive can be included.

#if DEBUG_LEVEL > 2
 /* ... */
#elif DEBUG_LEVEL == 2
 /* ... */
#else
 /* ... */
#endif

Conditional compilation can temporarily comment out large blocks of code for testing purposes.

#if 0
 /* Removed from compilation */
#endif

Compile if Defined

Two special operators can be used: defined and !defined (not defined).

#define DEBUG

#if defined DEBUG
 /* ... */
#elif !defined DEBUG
 /* ... */
#endif

#ifdef section is only compiled if the specified macro has been previously defined.

#ifndef stands for if-not-defined.

A macro is considered defined even if it has not been given a value.

#ifdef DEBUG
 /* ... */
#endif

#ifndef DEBUG
 /* ... */
#endif

Related Tutorials