jagttt
jagttt

Reputation: 1070

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

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?

Upvotes: 26

Views: 39522

Answers (6)

user214810
user214810

Reputation: 11

I've seen the following on the 'net: #define TRACE printf

Developing this a little bit, came up with the following:

#ifdef _DEBUG
#define TRACE printf
#else
#define TRACE 
#endif

Upvotes: 0

oHo
oHo

Reputation: 54581

Thanks to these answers I have fixed my bug :-)

Here I share my TRACE macro in C++ based on ideas from Ferruccio and enthusiasticgeek.

#ifdef ENABLE_TRACE
#  ifdef _MSC_VER
#    include <windows.h>
#    include <sstream>
#    define TRACE(x)                           \
     do {  std::stringstream s;  s << (x);     \
           OutputDebugString(s.str().c_str()); \
        } while(0)
#  else
#    include <iostream>
#    define TRACE(x)  std::clog << (x)
#  endif        // or std::cerr << (x) << std::flush
#else
#  define TRACE(x)
#endif

example:

#define ENABLE_TRACE  //can depend on _DEBUG or NDEBUG macros
#include "my_above_trace_header.h"

int main (void)
{
   int     v1 = 123;
   double  v2 = 456.789;
   TRACE ("main() v1="<< v1 <<" v2="<< v2 <<'\n');
}

Any improvements/suggestions/contributions are welcome ;-)

Upvotes: 2

sarat
sarat

Reputation: 11130

In my understanding wvsprintf has problem with formatting. Use _vsnprintf (or thcar version _vsntprintf ) instead

Upvotes: 1

Ferruccio
Ferruccio

Reputation: 100688

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. ;-)

Upvotes: 30

Ulf Lindback
Ulf Lindback

Reputation: 14170

If you use ATL you can try ATLTRACE.

TRACE is defined in afx.h as (at least in vs 2008):

// extern ATL::CTrace TRACE;
#define TRACE ATLTRACE

And ATLTRACE can be found in atltrace.h

Upvotes: 9

Fredrik Jansson
Fredrik Jansson

Reputation: 3804

You can try the DebugOutputString function. TRACE is only enabled in debug builds.

Upvotes: 4

Related Questions