next up previous contents index
Next: Comparison with LATEX Syntax Up: More About C++ Previous: Scope   Contents   Index

Headers and Pre-Processing

A C++ source file is compiled in multiple stages that occur transparently to the user. The first step, pre-processing, involves simple text replacement for file inclusion, macro expansion and conditional compilation. Next, the source is compiled and assembled: Human-readable language instructions are parsed, then represented in assembly language. Finally, the object files are linked: Function calls are resolved to hard-coded file offsets, possibly involving external library files, and the program instructions are packaged into an executable binary that the operating system can run.

Pre-processing is used much less in C++ than in C; the language itself supports safer and more featureful alternatives to macros, such as const variables and inline functions. File inclusion and conditional compilation are the chief uses of the pre-processor. Lines of the form

  #include <cstdlib>
  #include "epix.h"
cause the contents of a header file to be read into the source file. A header file contains variable and function declarations, statements that specify types and names but do not define actual data. Declarations tell the compiler just enough to resolve expressions and function calls without knowing specific values or function definitions.

Conditional compilation is similar to conditional LATEX code, and is best explained by example. A file might be used to produce both color and monochrome output as follows:

//#define COLOR  // uncomment for color
#ifdef COLOR
  ...  // code for generating color figure
#else
  ...  // monochrome code
#endif // COLOR
The ``compiler symbol'' COLOR is an ordinary C++ name; compilation is controlled by commenting or uncommenting the #define line. Multiple decisions on the same symbol may appear in a file. An #else block is optional, but every #ifdef must have a matching #endif. Commenting the #endif is a good habit; in a realistic file, the start and end of a conditional block may be separated by more than one screen.


next up previous contents index
Next: Comparison with LATEX Syntax Up: More About C++ Previous: Scope   Contents   Index
Andrew D. Hwang 2004-09-04