How to remove debug code at compile time in C ++?

Say I have a C ++ function debugPrint (int foo). How can I best remove this from releases? I don't want to surround every debugPrint call with #ifdefs, as that would be very time consuming. On the other hand, I want to be 100% sure that the compiler passes all calls to this function, and the function itself from the release build. A proofreading must also occur if it is called with a parameter that is the result of a function call. For example, debugPrint (getFoo ()) ;. In this case, I also want the getFoo () call to be deleted. I understand that inlining can be an option, but support is not guaranteed.

+4
source share
5 answers

Use conditional compilation and macro:

#ifdef _DEBUG #define LOG( x ) debugPrint( x ) #else #define LOG( x ) #endif 

Define _DEBUG for the debug build and do not define it for the build build. Now in the release, create each

 LOG( blahbhahblah ); 

will be expanded to an empty line - even the parameters will not be evaluated and will not be included in the emitted code.

You can use any pre-processor symbol that is already defined in the debug assembly and not defined in the version instead of _DEBUG .

+13
source

Make the function inline, and inside the function there is # ifdef, like this:

 inline void debugPrint(whatever_t wtvr) { #ifdef DEBUG Logger::log(wtvr); #endif } 

Thus, the optimizer will block the empty function, keeping the code clean.

+7
source

@sharptooth answer is good. However, one minor change that I usually make is to disable debugging if the NDEBUG macro NDEBUG not defined and the debug macro is not defined:

 #ifndef NDEBUG  #define LOG( x ) debugPrint( x ) #else  #define LOG( x ) #endif 

When the NDEBUG macro NDEBUG defined, then C assert s, which I prefer to use quite liberally to assert things like prerequisites and postconditions, or even to help clarify the result of complex logic, refuse to compile as Well. This is the standard "no debugging" macro. And the NDEBUG macro should already be defined in release builds.

See: http://www.opengroup.org/onlinepubs/009695399/functions/assert.html

+2
source

I did something like this before with a preprocessor.

 #ifndef DEBUG #define debugPrint #endif 

Essentially, this will delete all debug lines.

+1
source
 #ifdef _DEBUG #define debugPrint(x) _debugPrint(x) void _debugPrint(int foo) { // debugPrint implementation } #else #define debugPrint(x) #endif 
+1
source

All Articles