32

I have been using something like this:

int main(int argc, char *argv[])
{

#ifdef DEBUG
    printf("RUNNING DEBUG BUILD");
#else
    printf("Running... this is a release build.");
#endif
...

However this requires me to compile with -DDEBUG for the debug build. Does GCC give me some way for me to determine when I am compiling with debug symbols (-g flag) such as defining its own preprocessor macro that I can check for?

Steven Lu
  • 41,389
  • 58
  • 210
  • 364
  • 2
    I don't know for sure, but I highly doubt it. In theory, the preprocessing could be done in a separate pass with the `cpp` command before compilation, and the preprocessor has no notion of debugging symbols or the `-g` option. – Adam Rosenfield Mar 07 '11 at 18:06

2 Answers2

28

Answer is no. Usually these macros (DEBUG, NDEBUG, _DEBUG) are set by the IDE/make system depending on which configuration (debug/release) you have active. I think these answers can be of help:

C #define macro for debug printing

Where does the -DNDEBUG normally come from?

_DEBUG vs NDEBUG

Community
  • 1
  • 1
JoeSlav
  • 4,479
  • 4
  • 31
  • 50
  • I looked into NetBeans - it appears this IDE at least doesn't provide you with any specific debug flags, so I ended up doing a manual define ie -DDEBUG in the g++ command line (in project options) – Pete855217 Apr 16 '13 at 14:13
0

I think the answer that I was looking for was essentially what Adam posted as a comment, which is:

The compiler's job does not include preprocessing, and in fact the compiler will choke on any preprocessor switches not handled by the preprocessor that make their way into code.

So, because the way to branch code has to leverage the preprocessor, it means by the time the compiler gets any code it's already one or the other (debug code or release code), so it's impossible for me to do what my question asks at this stage (after preprocessor).

So it is a direct consequence of the preprocessor being designed as a separate process for feeding the code through.

Steven Lu
  • 41,389
  • 58
  • 210
  • 364
  • You have to have a different set of options for the compiler anyway, so why not ensure that the `NDEBUG` symbol is defined appropriately, too? – Michael Burr Jan 03 '15 at 07:50
  • Well, yes. why not. This is how it's taught, this is how it must be used, and this is the reasoning why it is like this. (conceptually and ideally, there should only be one flag that controls this, but in practice we must use both `-g` and `-DDEBUG`) – Steven Lu Jan 03 '15 at 08:33
  • Don't forget that having symbols doesn't mean it's a 'debug' or non-optimized build. Any type of build can have symbols generated. – Michael Burr Jan 03 '15 at 19:38