how to run only when debugging
John (Eljay) Love-Jensen
eljay@adobe.com
Fri Oct 12 18:47:00 GMT 2007
Hi Manal,
> I am looking for an ANSI C preprocessor directive that can make code run only when I am in debugging mode (compiled with gcc -g option)
gcc -g does not introduce a define, you have to do that yourself. As you can see from this diff:
diff <(gcc -g -E -dM -x c++ - <<<'' | sort) <(gcc -E -dM -x c++ - <<<'' | sort)
A rather widespread convention dating back to the misty dawn of time is that debug compiles *LACK* the NDEBUG preprocessor define (e.g., -UNDEBUG), and that release compiles declare the NDEBUG preprocessor define (e.g., -DNDEBUG).
So to compile your debug code, do this:
gcc -g
And to compile your release code, do this:
gcc -DNDEBUG
> I found something like:
#if DEBUG
Do this in debug;
#else
do this optionally if not in debug
#endif
Change that to:
#ifndef NDEBUG
Do this in debug;
#else
do this optionally if not in debug
#endif
> but it didn't work, as DEBUG is not defined,
Correct, since you did not define it.
For your team, you can adopt any of these other fairly prevalent conventions:
debug: gcc -g -DDEBUG
debug: gcc -g -D_DEBUG
release: gcc -DRELEASE
release: gcc -D_RELEASE
Note: _DEBUG is often seen in Microsoft C, C++, Visual C++ project debug builds, and NDEBUG in their release builds.
I prefer to use the NDEBUG indicating release, and absence of NDEBUG indicating debug.
debug: gcc -g -UNDEBUG
release: gcc -DNDEBUG
The <assert.h> or <cassert> headers are affected by the presence or absence of NDEBUG.
HTH,
--Eljay
More information about the Gcc-help
mailing list