How can I use the TRACE macro in non-MFC projects?

jagttt picture jagttt · Jan 30, 2009 · Viewed 34.8k times · Source

I want to use the TRACE() macro to get output in the debug window in Visual Studio 2005 in a non-MFC C++ project, but which additional header or library is needed?

Is there a way of putting messages in the debug output window and how can I do that?

Answer

Ferruccio picture Ferruccio · Jan 30, 2009

Build your own.

trace.cpp:

#ifdef _DEBUG
bool _trace(TCHAR *format, ...)
{
   TCHAR buffer[1000];

   va_list argptr;
   va_start(argptr, format);
   wvsprintf(buffer, format, argptr);
   va_end(argptr);

   OutputDebugString(buffer);

   return true;
}
#endif

trace.h:

#include <windows.h>
#ifdef _DEBUG
bool _trace(TCHAR *format, ...);
#define TRACE _trace
#else
#define TRACE false && _trace
#endif

then just #include "trace.h" and you're all set.

Disclaimer: I just copy/pasted this code from a personal project and took out some project specific stuff, but there's no reason it shouldn't work. ;-)