开发者

How to include code into the build only when a flag is set?

I have added some debugging code to my app which I want to call only when needed. I remember there is some kind of IFDEF that can be used to conditionally include code into a source file.

For example I might have something l开发者_StackOverflow中文版ike this:

IFDEF kDebugEnabled == YES {
    // some debugging code here
}

And then this piece of code is only compiled into the binary if that kDebugEnabled is YES.

How can I do something like this?

Please note: I don't want to use the project compiler flag settings. I just want to define a BOOL (or something that serves the purpose just as well) which is true or false and then just easily set it in my App Delegate for example. I find it hard to navigate to the project compiler settings, searching for a flag and then setting it. I know there is a Debug flag which might be of use.


What you are looking for is:

#ifdef __YOURSYMBOL__
  <conditional code>
#endif

You can programmatically define __YOURSYMBOL__ like this:

 #define __YOURSYMBOL__

__YOURSYMBOL__ can be any string that makes sense to you to remember why you are including/excluding that code snippet.

The DEBUG constant is a special preprocessor constant that the compiler defines specifically for you when the code is built for debugging, so you can simply use it:

#ifdef DEBUG
         <conditional code>
#endif

Take into account that this is the C-preprocessor, not C, nor Objective-C that you are using, so a test like kDebugEnabled == YES (where kDebugEnabled is an Objective-C variable) is simply not possible. You can define integer values for your constants, like this:

#define __LOG_LEVEL__ 3

and then test for it:

#if __LOG_LEVEL__ == 3
    ...
Endif


As far as I know, you can't have code in your classes that is not compiled into the final product without using compiler flags. However, using the DEBUG flag is a lot easier than you think. If you are using Xcode 4, it's set up for you by default.

#ifdef DEBUG

  // Your debug-only code goes here

#endif // DEBUG

Xcode has, by default, two configurations, Debug and Release. When you use the debug build configuration, among other things, it sets the DEBUG compiler flag, which you can then use to conditionally compile code. No need to mess with compilation settings at all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜