1

I am trying to find a way to prevent user from even compiling the code based on value of some user-defined build setting such as DEBUG=1. First thing that popped out in my mind is to write a macro something like this;

#if DEBUG=1
    #define NS_UNAVAILABLE_IN_PROD NSLog(x);
#else
    #define NS_UNAVAILABLE_IN_PROD
#endif

so I am able use it like this;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
   NS_UNAVAILABLE_IN_PROD

   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   self.window.backgroundColor = [UIColor blackColor];
}

When I try to compile the code, I get the error:

Use of undeclared identifier 'x'

which is expected, but in some cases, depending on the place where I put this check, a local variable x may be initialized before that so it passes without any error. Thus, I need a more clever way to inform user that the code can't be compiled because he is in DEBUG mode.

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
  • Careful using `#ifdef DEBUG`. If you have `DEBUG=0`, `#ifdef DEBUG` is still true. You want `#if DEBUG`. – rmaddy Dec 19 '14 at 23:56
  • Your question is unclear. What do you want to happen when `DEBUG=1`? Do you want to simply log a fixed message? – rmaddy Dec 19 '14 at 23:56
  • You fixed the code incorrectly. You want `#if DEBUG`. Then put the non-debug code in the `else` part and the debug code in the `if` part. – rmaddy Dec 20 '14 at 00:01

1 Answers1

2

If I understand the question you are looking for #error, e.g.:

#if DEBUG
#error "Will not compile"
#endif

After Comments

What I'm suggesting is you do:

#if DEBUG
#error "This method only available in production"
#endif
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
   self.window.backgroundColor = [UIColor blackColor];
}

It might be nice if you could define that as a macro itself, but I don't think you can.

You can place that code multiple times into a file.

You can also use _Static_assert as in the other question you've linked to:

#define DEBUG_ONLY _Static_assert (!DEBUG, "Only available in debug");

DEBUG_ONLY - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

but note you need to put it at the start of the line not at the end.

CRD
  • 52,522
  • 5
  • 70
  • 86
  • 1
    The OP seems to want a compilation error at a specific location in the code and probably at multiple locations. – rmaddy Dec 20 '14 at 00:04
  • http://stackoverflow.com/questions/3385515/static-assert-in-c This is very close to what I want to do but I don't know how to do it in obj-c. – Ozgur Vatansever Dec 20 '14 at 00:08
  • 1
    @ozgurv - I've updated the answer, maybe that will help – CRD Dec 20 '14 at 00:28