Chapter 9. Writing Macros

In This Chapter

  • Revisiting the Compilation Process

  • Creating constants using preprocessor Defines

  • Conditionally compiling portions of code based on compiler settings

  • Writing preprocessor macros to manipulate your code at compile time

The topic of this chapter is macros. Macros are a special feature of the Objective-C preprocessor that enable you to execute special commands or replace particular values in your code at compilation time. Macros are unique in that the commands are actually executed as part of the compilation process. The results of those commands are usually insertions of values or files, and so on. The term "macro" comes from the idea that something small can expand into something larger, and in a lot of ways, this is exactly what preprocessor macros do.

Reviewing the Compilation Process

I've discussed the compilation process before, but here I want to focus on the earliest stage of compilation called the preprocessor. The preprocessor, as its name implies, is a stage of compilation which happens prior to the actual processing of the bulk of the source code. Its job is primarily to take raw source files and prepare them for the compilation process itself.

To do this, it first strips out any comments in the source code, replacing them with spaces; then it performs any line transformations required. Finally, it expands any preprocessor directives, also known as macros.

A preprocessor directive is any line that begins with a # symbol, directly followed ...

Get Objective-C 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.