Sunday, December 27, 2009

Precompiler Defines

I had considered writing about this topic at one point, but discarded the idea as being too simple. I assumed it was already common knowledge.

In the last week, I've received two e-mails asking about this, so I decided it might be worth a quick post, even though many of you certainly know this already.

A lot of people like to put code in that is compiled into the debug version of their app, but not into the release version. Something along the lines of:

#ifdef DEBUG
NSLog(@"Some Debug Statement telling me the value of %@", foo);
#endif

I generally don't do much of this myself, preferring to use things like breakpoint actions for things that I don't want in my code. Personally, I want the code that gets compiled in Release and Debug builds to be as similar as possible to minimize unexpected surprises.

But, I recognize that this is a widely used approach that many people will want to use, and how you do it in Xcode isn't immediately obvious. If you open up the Project Info window by selecting Edit Project Settings from the Project menu, or double-clicking the project's root node in the Groups & Files pane, then click on the Build tab, you have the ability to set various options on a per-configuration basis. Under the heading GCC x.x - Preprocessing (where x.x is the version of GCC you are using), there is an option called Preprocessor Macros. You can define precompiler constants here on a per-configuration basis. Here's a screenshot that shows the value DEBUG being defined for the Debug configuration only:

Screen shot 2009-12-27 at 11.52.40 AM.png

The one problem with using this option is that defining a macro here triggers the precompiled headers to get re-compiled every time. Fortunately, the next option after Preprocessor Macros is called Preprocessor Macros Not used In Precompiled Headers, and it does exactly the same thing, only it doesn't define the macros until after the .pch file is read, meaning it won't trigger a recompile of the precompiled headers. That will result in shorter compile times. So, most of the time, this is what you want, unless you manually add something to the .pch file that relies on the macro:

Screen shot 2009-12-27 at 12.09.58 PM.png

No comments:

Post a Comment