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.
The lines that begin with # are directives that tell the preprocessor what to do.

A C++ macro is ancient history.

  1. const.C, const.txt
    In contemporary C++, we create a const variable.
  2. define.C, define.txt
    In ancient C and C++, we would have defined (i.e., created) a macro named PI.
    The name of a macro is traditionally all uppercase.
    The #define directive tells the C++ preprocessor to change every subsequent copy of the word PI to 3.14159265358979.
    Also demonstrating conditional compilation with
    1. #ifdef (“if the macro is defined”) and #endif
    2. #ifndef (“if the macro is not defined”) and #endif

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

  1. This C++ program is made of two .C files.
    1. main.C, main.txt
    2. file1.C
    To compile and run a multi-file program,
    c++ -o ~/bin/point main.C file1.C        (minus lowercase O space tilde)
    ls -l ~/bin/point
    
    point
    point p is (3, 4)
    etc.
    
  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, main.txt
    3. file1.C
    When you write an #include directive,
    1. #include with <angle brackets> looks in the directory /usr/include/c++/15 (on our machine storm.cis.fordham.edu) for the header file.
    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++ -o ~/bin/point main.C file1.C
    ls -l ~/bin/point
    
    point
    point p is (3, 4)
    

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 {
          |        ^~~~~
    
  2. We could render this multiple inclusion harmless by changing the above point.h to this point.h.
    The preprocessor lines in this file are called an include guard.
    This would allow point.h to be included more than once, and the compiler would pay attention to it ony the first time it is included.