sivabudh
sivabudh

Reputation: 32645

C / C++ : Portable way to detect debug / release?

Is there a standardized (e.g. implemented by all major compilers) #define that will allow me to distinguish between debug and release builds?

Upvotes: 28

Views: 28409

Answers (4)

mpen
mpen

Reputation: 282915

Best I could come with is

#ifndef NDEBUG
// Production builds should set NDEBUG=1
#define NDEBUG false
#else
#define NDEBUG true
#endif

#ifndef DEBUG
#define DEBUG !NDEBUG
#endif

Then you can wrap your debug code in if(DEBUG) { ... }.

Upvotes: 0

KeithB
KeithB

Reputation: 17027

Since there is no standard definition of debug or release, there isn't a way to do this. I can think of at least four different things that could be meant, and they can all be changed independently. Only two can be tested from within the code.

  1. Compiler optimization level
  2. Debugging symbols included in binary (these can even be removed at a later date)
  3. assert() enabled (NDEBUG not defined)
  4. logging turned off

Upvotes: 5

John Knoeller
John Knoeller

Reputation: 34148

if believe

 #ifdef NDEBUG
  // nondebug
 #else
  // debug code
 #endif

is the most portable.

But no compiler knows whether you are compiling debug or release, so this isn't automatic. But this one is used by assert.h in the c-runtime, so it's quite common. Visual Studio will set it, and I'm sure most other IDE's will as well.

Upvotes: 30

t0mm13b
t0mm13b

Reputation: 34592

Edit: I misread the question and waffled off on a different tangent!!! Apologies... The macro _NDEBUG is used on Linux as well as on Windows...

If the binary is built and you need to determine if the build was release/debug, you can get a hexadecimal dump, if you see loads of symbols in it that would be debugging information...for example, under Linux, using the strings utility. There is a version available for Windows by SysInternals, available here on technet. Release versions of binary executables would not have the strings representing different symbols...

strings some_binary

Hope this helps, Best regards, Tom.

Upvotes: 1

Related Questions