he C Preprocessor :: Overview

The C Preprocessor :: Overview

  • The C Preprocessor is not part of the compiler, but is a separate step in the compilation process. In simplistic terms, a C Preprocessor is just a text substitution tool. We'll refer to the C Preprocessor as the CPP.
  • All preprocessor lines begin with #. This listing is from Weiss pg. 104. The unconditional directives are:
    • #include - Inserts a particular header from another file
    • #define - Defines a preprocessor macro
    • #undef - Undefines a preprocessor macro
    The conditional directives are:
    • #ifdef - If this macro is defined
    • #ifndef - If this macro is not defined
    • #if - Test if a compile time condition is true
    • #else - The alternative for #if
    • #elif - #else an #if in one statement
    • #endif - End preprocessor conditional
    Other directives include:
    • # - Stringization, replaces a macro parameter with a string constant
    • ## - Token merge, creates a single token from two adjacent ones
  • Some examples of the above:
      #define MAX_ARRAY_LENGTH 20
    Tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability. Notice the absence of the ;.
      #include 
    #include "mystring.h"
    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 add the text to the file. This is a difference you must take note of.
      #undef MEANING_OF_LIFE
    #define MEANING_OF_LIFE 42
    Tells the CPP to undefine MEANING_OF_LIFE and define it for 42.
      #ifndef IROCK
    #define IROCK "You wish!"
    #endif
    Tells the CPP to define IROCK only if IROCK isn't defined already.
      #ifdef DEBUG
    /* Your debugging statements here */
    #endif
    Tells the CPP to do the following statements if DEBUG is defined. This is useful if you pass the -DDEBUG flag to gcc. This will define DEBUG, so you can turn debugging on and off on the fly!

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post