Text Substitution

The preprocessor is a tool that C++ programmers use to manipulate the contents of source code files prior to compilation. In the most general sense, the preprocessor performs text substitution and text modification. Higher-level features emerge when we consider the overall effect of these rather basic manipulations. File inclusion, macro substitution, and conditional compilation are three higher-level features the preprocessor provides to a programmer.

Source code files, as authored by programmers, typically need to be modified in various ways before compilation can take place. Because programmers rely on the preprocessor to perform these modifications, knowledge of the basic use of the preprocessor is essential. Since C++ programs consist entirely of text, a programmer must use the preprocessor to include the declarations of external classes or functions. This is known as file inclusion. The use of other preprocessor features, such as macro substitution, is not necessarily required. Macros exist as a convenience to the programmer. They also provide backward compatibility with C programs.

A programmer interacts with the preprocessor through commands called preprocessor directives. Beginning with the number sign (#), preprocessor directives are single-line commands a programmer places into a source code file. Since preprocessor directives are not C++ code, they do not follow the language's scoping rules and therefore can appear on any line in a source code file. The appearance of a preprocessor directive in a source code file instructs the preprocessor to perform some action. The action the preprocessor takes depends on the directive. For some directives, the preprocessor makes exactly one modification in the source code file. An example of this is file inclusion where the preprocessor includes the contents of another file into the file being processed. Preprocessor directives used to define other tasks, such as a macro substitution, can cause the preprocessor to make several modifications in a source code file.

The Java language does not have a tool similar to the C++ preprocessor. Instead, Java provides language mechanisms that accomplish the same tasks that the C++ processor performs. One example is the import statement. Using import statements, a Java programmer specifies the external classes and packages a program requires.