Search code examples
iphoneobjective-ciosipadconditional-compilation

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 like 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.


Solution

  • 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