Thursday, April 3, 2008

How do I send trace messages to the debug console in Visual Studio?

If you are not using MFC or ATL then there are some basic macros in crtdbg.h that allow you to write to the debug console in Visual Studio. The only problem is that they are not very user friendly - you have to use a different macro depending on how many parameters you have in your formatted string. I suspect that the reason behind this is that prior to the C99 specification there was no support for variadic macros. However, now that almost all compilers are C99 compliant, it is probably worth using a more convenient trace command for debugging purposes. The following macro works just like printf except that it sends its output to the debug console.
#include <stdio.h>
#include <crtdbg.h>
#define TRACE(...) \
do{ \
char *__trace = NULL; \
int len = 1+_scprintf(__VA_ARGS__); \
__trace = (char*)malloc(len*sizeof(char)); \
sprintf_s(__trace, len, __VA_ARGS__); \
_RPT0(_CRT_WARN, __trace); \
if(__trace != NULL) \
free(__trace); \
} while(0)
This uses the do-while trick so that the calling syntax includes a trailing semicolon. This will only work when you compile with the debug version of the C runtime libraries (/MTd for example).

No comments: