6.13. The Preprocessor

Now you are going to cover a topic that isn't really part of the C language at all: the C preprocessor. A preprocessor is a program that goes through a piece of code before it is passed to the compiler, and modifies it. The C preprocessor is heavily used by C programmers, and derived variants like C++ and Objective-C.

On Mac OS X, the standard C compiler is gcc, which is part of the GNU Compiler Collection (GCC). To confuse matters, the preprocessor is part of gcc, so you may not even realize that you are using it. Usually it runs before the compiler automatically. If you want to use the gcc preprocessor without compiling afterward, you can pass the -E -P options.

The C preprocessor is used for a range of tasks, most of which ensure that compilation can proceed without a hitch. Here are some ways in which the C preprocessor is used:

  • To incorporate the source code of one file in another file.

  • To include different code based on some condition, such as whether you are debugging.

  • To replace a macro label wherever it is found with a piece of code. For example, replacing PI with a number like 3.1415972.

In this section, you learn how you can achieve these goals with the C preprocessor.

When you communicate with the preprocessor in your source code, you give it directives. These are commands to do something, and they are all preceded by a # symbol. The first directive, and probably most widely used, is #include. Its purpose is to tell the preprocessor to include ...

Get Beginning Mac OS® X Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.