Debug macro

some notes about the debug macro

The debug macro is conveninet to in c/cpp program, sometimes, you want to hide these informations in delease version, sometimes you need to use them again when there is bug info. this is an example

#include <iostream>
#ifdef DEBUG_BUILD
# define DEBUG(x) std::cerr << x << std::endl;
#else
# define DEBUG(x) do {} while (0)
#endif

int main(){
char str[256];
sprintf(str, "self define %d", 123);
DEBUG(str);
DEBUG("debug point");
DEBUG("debug point function name: " << __PRETTY_FUNCTION__);

return 0;
}

The only necessary thing is to add the parameter -DDEBUG_BUILD when building the program. If the program is compiled by the cmake, just follow this answer, there are multiple ways to set it, such as:

SET(CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")

Another simple case is just to use the

#ifdef DEBUG_MACRO
// some debug messages
#endif

for a quick testing, when the code is ok and do not use the debug messages, we just not define it. If we need a version that does not contain the debug message, we just does not set associated parameters.

Or using the macro command as a wrapper for whatever is printed out. This is a more flexible way:

#ifdef USE_LOG
#define LOG(x) x
#else
#define LOG(x)
#endif

Just using the LOG macro to wrap whatever needed to specify by the print command.

推荐文章