Magic variables for tracing
February 14th, 2008
You often need tracing for debugging a application or just to keep an eye on the progress (e.g. drawing / data reading or something similar).
I mostly use this simple function or a bit modified one if needed:
void Debugging::Trace(char* szTmp, ...) { char msgbuf[256]; my_list args; my_start(args, szTmp); vsnprintf(msgbuf, 255, szTmp, args); my_end(args) ; fprintf(stdout, "Trace: %s\n", msgbuf); }
By the way, for me tracing is sometimes the only way when debugging drawing progress ’cause as the debugger appears the frame for drawing gets hidden. When the drawing frame is shown again it forces a redraw. That really sucks when trying to step through OnDraw/OnPaint events…
To improve tracing for more detailed results you can use magic variables which hold some useful information.
The probably best known of these is __func__, which is part of the C99 standard.
It’s equal to __FUNCTION__ and hold the name of the current function. For maximum portability it’s recommented to use __func__.
When programming in C __PRETTY_FUNCTION__ is just another alias for __FUNCTION__, but when using C++ it gives plenty of information about the function. Instead of just holding the name it holds also its signature:
bool HasValue(int x) { cout << "__FUNCTION__: " << __FUNCTION__ << endl; cout << "__PRETTY_FUNCTION__: " << __PRETTY_FUNCTION__ << endl; return true; }
Prints:
__FUNCTION__: HasValue __PRETTY_FUNCTION__: bool HasValue(int)
The last two are very common but significant for hard to debug codeparts like those you sometimes have for example in multi-threaded applications.
__LINE__ is for the current line and __FILE__ as expected for the source file.
I usually just need them for asserts:
if ( !assert(mainobject) ) throwMsg( "Assertion failed on line %d of file %s\n", __LINE__, __FILE__ );
It maybe relevant for you to know that I didn’t test those non-preprocessor makros on many different compilers. Most of them do work with VS compiler, all of them with GCC, but I’m pretty sure that compilers like Borland provide very similar makros.





