News & UpdatesProgrammingWeb programmingStoreMy Projects
Links
Affiliates

C++ Tutorial – 28 – Preprocessor II

Conditional compilation directives

The directives used for conditional compilation can include or exclude part of the source code if a certain condition is met. First, there is the #if and #endif directives, which specifies a section of code that will only be included if the condition after the #if directive is true. Note that this condition must evaluate to a constant expression.

#define DEBUG_LEVEL 3
 
#if DEBUG_LEVEL > 2
 // …
#endif

Just as with the C++ if statement, 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

Compile if defined

Sometimes, a section of code should only be compiled if a certain macro has been defined, irrespective of its value. For this purpose two special operators can be used: defined and !defined (not defined).

#define DEBUG
 
#if defined DEBUG
 // …
#elif !defined DEBUG
 // …
#endif

The same effect can also be achieved using the directives #ifdef and #ifndef respectively. For instance, the #ifdef section is only compiled if the specified macro has been previously defined. Note that a macro is considered defined even if it has not been given a value.

#ifdef DEBUG
 // …
#endif
 
#ifndef DEBUG
 // …
#endif

Error directive

When the #error directive is encountered the compilation is aborted. This directive can be useful for example to determine whether or not a certain line of code is being compiled. It can optionally take a parameter that specifies the description of the generated compilation error.

#error Compilation aborted

Line directive

Another standard directive is #line, which can be used to change the line number that is displayed when an error occurs during compilation. Following this directive the line number will as usual be increased by one for each successive line. The directive can take an optional string parameter that sets the filename that will be shown when an error occurs.

#line 5 "My MyApp Error"

Pragma directive

The last standard directive is #pragma, or pragmatic information. This directive is used to specify options to the compiler. For example, #pragma message can be used to have the compiler output a string to the build window. Another argument for this directive is warning, which changes how the compiler handles warnings.

// Show compiler message
#pragma message( "Hello Compiler" )
 
// Disable warning 4507
#pragma warning(disable : 4507)
Recommended additional reading:
Sams - Teach Yourself C++ in One Hour a Day