If you find this article contains errors or problems rendering it unreadable (missing images or files, mangled code, improper text formatting, etc) please contact the editor so corrections can be made. Thank you for helping us improve this resource
(Editor's Note: Source code for this article is currently not available)
This is a short little snippet whose purpose is to aid in debugging, by keeping track of which function the thread of execution is currently in, using a staticly allocated doubly-linked list (for performance reasons).
To use, include CallStackTrace.h (this file) and CallStackTrace.cpp in your project. Then, ensure that in any source file that you'd like to trace the stack you put
near the top.
Then, to enable the stack tracing, at the top of the function (preferrably the first line of the function), put
where functionName is (obviously) the name of the function being traced. Then, at the end of the function, put
The only function you shouldn't have to put that in is the main() function. Note that no functionName is required.
If an error occurs, just call CallStackTrace::Dump() to dump the current call stack (with file names and line numbers) to stdout. You can optionally pass a std::ostream to CallStackTrace::Dump() to dump the stack trace to a file or other ostream derived object.
Catching Unhandled Exceptions
To report the call stack when an unhandled exception is thrown, structure your main() function like the following:
run program here
cout << "Unhandled Exception!" << endl;
Handling "Expected" Exceptions
"But wait!" you say. "What if I handle an exception in a catch() block? Well, in that case, just make the first line of your catch block the TRACE_UNWIND() macro (no function name needed, as long as it has a TRACE_ENTER_FN(functionName) at the top of the function). That will unwind the Call Stack Trace, and allow normal functioning from that point forward.