Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip debug code during compile time in C++?

Tags:

c++

Say I have a C++ function debugPrint(int foo). How can I most conveniently strip that from release builds? I do not want to surround every call to debugPrint with #ifdefs as it would be really time consuming. On the other hand, I want to be 100% sure that the compiler strips all the calls to that function, and the function itself from release builds. The stripping should happen also, if it's called with a parameter that results from a function call. E.g., debugPrint(getFoo());. In that case I want also the getFoo() call to be stripped. I understand that function inlining could be an option, but inlining is not guaranteed to be supported.

like image 627
juvenis Avatar asked Nov 29 '22 12:11

juvenis


1 Answers

Use conditinal compilation and a macro:

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

Define _DEBUG for the debug build and not define it for the release build. Now in release build every

LOG( blahbhahblah );

will be expanded into an empty string - even the parameters will not be evaluated and will not be included into the emitted code.

You can use any already existing preprocessor symbol that is defined in debug build and not defined in release instead of _DEBUG.

like image 140
sharptooth Avatar answered Dec 08 '22 00:12

sharptooth