tags:

views:

100

answers:

1

how call TRACE in c++?please explain for example with this simple code

int x = 1;
int y = 16;
float z = 32.0;
TRACE( "This is a TRACE statement\n" );

TRACE( "The value of x is %d\n", x );

TRACE( "x = %d and y = %d\n", x, y );

TRACE( "x = %d and y = %x and z = %f\n", x, y, z );
+3  A: 

If you mean "How can I trace the execution path of my code?" Then you need to use a source-level symbolic debugger.

In Linux this generally means using GDB for which there a number of GUI front ends; using GDB on the command line is arcane and laborious, it can be used through Eclipse or KDevelop for example, or the stand-alone Insight debugger. In Windows, the debugger will be specific to the compiler, but VC++ has about the best debugger available (and for free in the Express Edition).

In response to davit's edit

Define a TRACE macro thus:

#if defined NDEBUG
    #define TRACE( format, ... )
#else
    #define TRACE( format, ... )   printf( "%s::%s(%d)" format, __FILE__, __FUNCTION__,  __LINE__, __VA_ARGS__ )
#endif

Note that the lack of a comma between "%s::%s(%d)" and format is deliberate. It prints a formatted string with source location prepended. I work in real-time embedded systems so often I also include a timestamp in the output as well.

Clifford
"In Windows, it will be compiler specific".. And they all call the Windows API method OutputDebugString which allows external tools (like debuggers) to read the output.
Tergiver
@Tergiver: I was referring to the the fact that the symbolic debugger would be specific to the compiler (since there is no single de-facto C++ compiler as there is in Linux), not the method of outputting a debug string. That part of the answer was posted before davit's explanatory example and was not related to output of debug strings since before the example was posted, it was not clear what he intended.
Clifford
@James McNellis: Thanks for the edit; that is what I meant, but I pasted it form some old GCC 2.95 code I had from an old project and never noticed the non-standard variadic macro syntax.
Clifford
One thing that caught me off guard when I used such a macro was the fact that `format` has to be a string literal. It rarely matters, but as I recall the error message that resulted was rather cryptic.
Dennis Zickefoose
@Clifford: I thought the original question was, "How do I create a TRACE macro?" After all the edits, I'm even less clear what the actual question is.
Tergiver
@Dennis: Yes that is true, although variable format strings are considered dangerous in any case (http://en.wikipedia.org/wiki/Format_string_attack), and should be avoided. Cryptic error message are one of the reasons that macros are also a bad idea in general too!
Clifford