C++ Preprocessor: The Code in the Middle (Page 1 of 6 )
In this article, we examine instructions given to the preprocessor and see how they are used in general. The preprocessor handles your code before the compiler interprets it. If you have been wondering just what the preprocessor is used for, this article explains.
Whence and what art thou, execrable shape?
[John Milton 1608-1674]
The Preprocessor and the Compiler
Before the compiler interprets your code, the preprocessor handles it. Its task is to scan through your code and to look for preprocessor instructions; these can for example be used to replace certain tokens with string or numerical values, or to blank out complete sections of the code before the compiler sees it. You can recognize these instructions from the pound (#) symbol that needs to precede every preprocessor instruction.
We are going to examine these instructions and see how they are used in general. Most probably you have been using at least one of them without giving it much thought: ‘#include’. Still, this is an instruction that is handled by the preprocessor and not by the compiler. It tells it to replace the directive with the contents of the file named after it.
One of the problems a large C++ project can face is long compilation time. This can happen when ‘#include’ is used carelessly; to compile a single source, the preprocessor might (indirectly) be pasting thousands of lines of headers in front of it!
When you use third party libraries like STL-port or Boost, you will find that macros can be very useful for building different code configurations. If you have to write portable C++ code you won’t be able to live without them… however you will most probably have grown to dislike them as well.
Don’t be misled by the fact that preprocessor macros may look deceptively simple. As I’ve said before, with C++ things can become as complex as you want them to be, and to be frank, a lot of great code I have seen involved the use of macros one way or another. Maybe this is because they provide the possibility of extending the language in such a cheeky (and sneaky) way.
Let's not get ahead of ourselves. We'll first look at what the preprocessor is used for most: string substitution and conditional compilation.
Next: String Substitution >>
More C++ Articles
More By J. Nakamura