O'Reilly logo

Just Enough C/C++ Programming by Guy W. Lecky-Thompson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Conditional Compilation with #if

In previous examples, you used the #ifdef statement to test whether or not a constant is defined. You also looked at #else and #endif as well as #ifndef to test whether a constant is not defined. You will probably not be surprised to learn that pre-processor directives include a whole decision-making mechanism that mirrors the conditional execution mechanism (if .. elseif .. else).

So combined with the defined function, you can build code with the same functionality as the multiple-include-prevention mechanism using #if:

#if !defined (_FILENAME_H)
#define _FILENAME_H
    // This code will be processed only once
    // per compilation cycle
#endif

You can also use a similar mechanism to specify a debug level, as well as ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required