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.
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
.
const.C
.
Nowadays, we would use a
const
variable instead of a macro.
c++ main.C date.C
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’
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?
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++.
#
)
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
#include
d (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
#include
d,
and false on all subsequent times.