tags:

views:

148

answers:

3

Is there any mechanism in D (D2) to force code to be compiled out during a release build?

In C, you might have something like

#ifndef NDEBUG
/*Something that will only run in a debug build*/
#endif

I know that D has

debug(mymodule) {
   //Do something
}

But this requires the user to pass -debug for each module to enable it.

I'm looking for a global mechanism that will always run the code in a normal build but compile it out when you pass the -release flag. I know some built-ins have this ability (e.g. assert), but is there any way for user code to do it too?

+1  A: 

If no better answer is found, a hackaround like this should work: bool debugMode() { bool res; assert(!!(res = true)); return res; }

FeepingCreature
I don't see how that works.
BCS
That's assignment inside the assert. In release mode, the assert and its contents are compiled out. Thus, the assignment only takes place in non-release builds.
DK
the OP is looking for a compile time solution and assert doesn't ever come out in CTFE.
BCS
+2  A: 

dmd -release -version=dist module.d

and

version(dist) {} else {
    int i = 9;
}

Best I can think of.

[update]

Personally, I think the above answer is "bad". The above solution would introduce overly complex logic into the release process, which I think should be straight forward and predictable. I'd recommend just using -debug and debug{ //... }. Even if you feel you might forget adding the debug-flag when you're compiling—you're just devving!—mistakes are cheap. Mistakes that make it into the release are worse.

0scar
It's not quite as ideal as I had hoped for, since you need to remember to specify the -version flag, but those details can probably be hidden from the end user inside the build system, so it'll do.
JRM
Thanks BCS for the correction.
0scar
+7  A: 

There is a global notion of debug. Just write:

debug { ... code ... }

Andrei
I knew there had to be something simple like this. The D Programming Language only mentioned the module-specific debug, so I hadn't realized there was a global one too. Now I can use debug {...} for basic debugging and debug(mymodule) {...} to add more detailed debugging.
JRM
Exactly. Apologies for the omission. I have added an erratum on your behalf here: http://www.erdani.com/tdpl/errata/
Andrei