The C Preprocessor

The C++ preprocessor is a text editor that automatically edits the C++ program. When you give the c++ command to translate your C++ program into terms the computer can understand and execute, the c++ command begins by running the C++ preprocessor.

A macro is ancient history

  1. define.C. Define (i.e., create) a macro named PI. Traditional to give an uppercase name to a macro. The #define directive tells the C++ preprocessor to change every subsequent copy of the word PI to 3.14159.
  2. const.C. Nowadays, we would use a const variable instead of a macro.

Can’t paste in the same header file twice

  1. Compile this three-file program with
    c++ main.C date.C
    
    1. date.h (the header file for class date) holds the declaration for class date.
    2. date.C (the implementation file for class date) holds the definitions for the member functions and friend functions, and static data members, of class date.
    3. main.C holds the rest of the program.
  2. If the above file main.C accidentally said
    #include "date.h"
    #include "date.h"
    
    we would get an error message because the class declaration
    class date {
    	//etc.
    };
    
    would be pasted into the program twice.
    error: redefinition of ‘class date’
    Few people would make this mistake.
  3. But the same problem would arise if the file main.C said
    #include "date.h"
    
    and the file iostream also said
    #include "date.h"
    
    How can we get the computer to pay attention to the content of the header file date.h only the first time it is pasted into the program?

Render a second inclusion harmless

  1. ifdef.C. In this example, the macro HIGH_PRECISION is intended for use only in a #ifdef directive. The #ifdef, #else, #endif directives tell the preprocessor that certain lines are to be included in, or excluded from, the program. This is called conditional compilation, and is the only use that macros still have in C++.
  2. The preprocessor directives (the lines that start with #) at the top and bottom of the header file date.h allow the computer to see the content of this file only the first time the file is #included (i.e., pasted) into the C++ program. Subsequent paste-ins are ignored and harmless.

    The directive #ifndef DATE_H means “pay attention to the following lines (up to the next #endif) only if no macro named DATE_H has been defined.” That will be true the first time date.h is #included, and false on all subsequent times.