Monday, December 10, 2007

The C Preprocessor

The C Preprocessor is a separate step in the compilation process, but not part of the compiler.


C Preprocessor is just a text substitution tool and we'll refer to the C Preprocessor as the CPP.



--------------------------------------------------------------------------------

The C Preprocessor

All preprocessor lines always begin with #. This listing is from Weiss pg. 104. The unconditional directives are as follows:
#define - Define a preprocessor macro
#include - Insert a particular header from another file
#undef - Undefine a preprocessor macro
The conditional directives are as follows:
#ifndef - If this macro is not defined
#ifdef - If this macro is defined
#if - Test if a compile time condition is true
#elif - #else an #if in one statement
#else - The alternative for #if
#endif - End preprocessor conditional
Other directives include:
## - Token merge, creates a single token from two adjacent ones
# - Stringization, replaces a macro parameter with a string constant




--------------------------------------------------------------------------------

Some examples of the above is given below:
#define MAX_ARRAY_LENGTH 20

The above code will tell the CPP to replace instances of MAX_ARRAY_LENGTH with 20. To increase readability,use #define for constants.



--------------------------------------------------------------------------------

#include
#include "mystring.h"

The above code tells the CPP to get stdio.h from System Libraries and add the text to this file. The next line tells CPP to get mystring.h from the local directory and then add the text to the file.



--------------------------------------------------------------------------------

#undef MEANING_OF_LIFE
#define MEANING_OF_LIFE 42

The above code tells the CPP to undefine MEANING_OF_LIFE and define it for 42.



--------------------------------------------------------------------------------

#ifndef IROCK
#define IROCK "You wish!"
#endif


The above code tells the CPP to define IROCK only if IROCK isn't defined already.



--------------------------------------------------------------------------------

#ifdef DEBUG
/* Your debugging statements here */
#endif


Thed above code tells the CPP to do the following statements if DEBUG is defined.If you pass the -DDEBUG flag to gcc,this is useful .