Search This Blog

Wednesday, July 28, 2010

Preprocessing directives


A C++ program consists of several types of preprocessing directives and statements. Preprocessing
directives are interpreted before compilation, must be limited to one line of text, are all prepended by
a hash character ‘#’ and do not necessarily terminate with a semicolon character ‘;’. The purpose of
preprocessing directives is mostly to enable conditional compilation and include other source files in the
current compilation. Some examples:
#define MYCONSTANT 10
#include
#include "myheader.h"
#ifdef DEBUG
const char version[] = "Debug";
#else
const char version[] = "Release";
#endif
The first line defines a constant called MYCONSTANT to take the value 10. Each time the string “MYCONSTANT”
appears in the rest of the program being compiled, it will be replaced by the string “10”.
The purpose of isolating constants to the beginning of the source file, where all the #defines are usually
kept, is to avoid having to hunt for constants within the whole file each time the constant is changed.
Although #defines are very popular in the C language, in C++ one usually uses equivalent constructs
which are not preprocessing directives, such as
const int MYCONSTANT = 10;
which is a normal C++ statement. The second line instructs the compiler to look for a file called iostream
within the compiler’s include search path (i.e. a predetermined list of paths within the filesystem where
a lot of include files are stored; typically, on Unix systems, this is /usr/include:/usr/local/include),
read it, and compile it as if it was part of the source code being compiled. The third line is similar to
the second but the slightly different syntax indicates that the file myheader.h is a user-created file and
probably resides in the current directory. Lines 4-8 are a conditional preprocessing directive, instructing
the compiler to define the character array version differently according as to whether the preprocessing
symbol DEBUG was defined or not when the compiler was called. It is possible to define such symbols
either explicitly, by including a preprocessor directive #define DEBUG before the conditional statement,
or implicitly by launching the compiler from the shell with the -DDEBUG option.

No comments:

Post a Comment