The C Preprocessor

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. The C++ preprocessor is a text editor that automatically edits the C++ program.

A C++ macro is ancient history

  1. define.C, define.txt.
    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.14159265358979.
  2. const.C, const.txt.
    Nowadays, we would use a const variable instead of a macro.
  3. ifdef.C, ifdef.txt. Conditional compilation with #ifdef.

A multi-file C++ program, with a header file

  1. This C++ program is made of two .C files. It produces no output.
    1. main.C
    2. file1.C
    To compile a multi-file program,
    c++ main.C file1.C
    ls -l a.out
    
  2. This C++ program is made of two .C files and one .h (header) file. It produces no output.
    1. point.h
    2. main.C
    3. file1.C
    When you write an #include directive,
    1. #include with <angle brackets> looks in the directory /usr/include/c++/15 for the header file (on our machine storm.cis.fordham.edu).
    2. #include with "double quotes" looks in your current directory for the header file.
    To compile this program, type the names of the .C files, but not the name of the .h file:
    c++ main.C file1.C
    

Include the same header file twice (by accident)

  1. In the above program, what would go wrong if the main.C file accidentally included the header file twice?
    //In main.C.  No reason to do this.
    #include "point.h"
    #include "point.h"
    
    c++ main.C file1.C
    In file included from main.C:4:
    point.h:1:8: error: redefinition of ‘struct point’
        1 | struct point {
          |        ^~~~~
    In file included from main.C:3:
    point.h:1:8: note: previous definition of ‘struct point’
        1 | struct point {
          |        ^~~~~
    
    We could render this multiple inclusion harmless by changing point.h to this point.h.
  2. This would allow point.h to be included more than once, and the compiler would pay atention to it ony the first time it is included.