Sign in to follow this  
Endar

Preprocessor blocks for debugging

Recommended Posts

Endar    668
In one of my pieces of code, I find that I'm using quite a few "#ifdef _DEBUG" preprocessor blocks, and I find it fairly interruptive when I'm looking at code. I still haven't figured out how to use VC++'s debugger properly, and anyway, inside the blocks, I'm writing to a log file. Has anyone found a more elegant way of doing something like this?

Share this post


Link to post
Share on other sites
SiCrane    11839
Since you're using MSVC, I would recommend looking at the source of the TRACE macro and see how it handles things.

Share this post


Link to post
Share on other sites
doynax    850
Some variation on this setup might work:

#ifndef NDEBUG
struct logger {
logger(const char *file, unsigned line) {
fprintf(stderr, "%s[%d] :: ", file, line);
}

void message(const char *format, ...) {
va_list args;

va_start(args, format);
vfprintf(stderr, format, args);
va_end(args);
fputc('\n', stderr);
}
};
# define log logger(__FILE__, __LINE__).message
#else
void logger(const char *format, ...) { }
# define log if(false) logger
#endif
edit: I just realized that the logger's arguments will be evaluated anyway and I can't seem to find a decent workaround right now. Any suggestions? This should work..

Share this post


Link to post
Share on other sites
Verg    450
The previous solution was good. Here's what I use:


#ifdef _DEBUG
#ifndef LOG_0
#define LOG_0(a) Win32DebugLog::log(a)
#define LOG_1(expr,a,b) Win32DebugLog::log(expr,a,b)
//et cetera
#endif
#else // NDEBUG
#ifndef LOG_0
#define LOG_0(a)
#define LOG_1(expr,a,b)
// and so on
#endif
#endif



Substitute your class name for Win32DebugLog, of course.

Then just pepper these through your code, and they will only log to your file in Debug mode:

LOG_1("Variable x = %d",100,x); // 100 = approx. size of final string

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this