views:

1065

answers:

4

In MFC C++ (Visual Studio 6) I am used to using the TRACE macro for debugging. Is there an equivalent statement for plain win32?

+2  A: 

From the msdn docs, Macros for Reporting:

You can use the _RPTn, and _RPTFn macros, defined in CRTDBG.H, to replace the use of printf statements for debugging. These macros automatically disappear in your release build when _DEBUG is not defined, so there is no need to enclose them in #ifdefs.

Gordon Wilson
+4  A: 

_RPTn works great, though not quite as convenient. Here is some code that recreates the MFC TRACE statement as a function allowing variable number of arguments. Also adds TraceEx macro which prepends source file and line number so you can click back to the location of the statement.

Update: The original code on CodeGuru wouldn't compile for me in Release mode so I changed the way that TRACE statements are removed for Release mode. Here is my full source that I put into Trace.h. Thanks to Thomas Rizos for the original:

// TRACE macro for win32
#ifndef __TRACE_H__850CE873
#define __TRACE_H__850CE873

#include <crtdbg.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>

#ifdef _DEBUG
#define TRACEMAXSTRING 1024

char szBuffer[TRACEMAXSTRING];
inline void TRACE(const char* format,...)
{
 va_list args;
 va_start(args,format);
 int nBuf;
 nBuf = _vsnprintf(szBuffer,
       TRACEMAXSTRING,
       format,
       args);
 va_end(args);

 _RPT0(_CRT_WARN,szBuffer);
}
#define TRACEF _snprintf(szBuffer,TRACEMAXSTRING,"%s(%d): ", \
    &strrchr(__FILE__,'\\')[1],__LINE__); \
    _RPT0(_CRT_WARN,szBuffer); \
    TRACE
#else
// Remove for release mode
#define TRACE  ((void)0)
#define TRACEF ((void)0)
#endif

#endif // __TRACE_H__850CE873
jacobsee
Nice, that's a useful snippet.
Gordon Wilson
szBuffer should not be global if you are using TRACE in more than one thread
Anders
good point -- I think if I just move the declaration inside the TRACE function it will break the TRACEF macro though -- is this true?
jacobsee
+3  A: 

There is also OutputDebugString. However that will not be removed when compiling release.

Bob
+1  A: 

Trace macros that provide messages with source code link, run-time callstack information, and function prototype information with parameter values:

Extended Trace: Trace macros for Win32

Aaron