General Purpose Call Stack Tracer
by Bryan Ross

Get the source code for this article here

Introduction

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

Usage

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

#include "CallStackTrace.h"

near the top.

Then, to enable the stack tracing, at the top of the function (preferrably the first line of the function), put

TRACE_ENTER_FN(functionName)

where functionName is (obviously) the name of the function being traced. Then, at the end of the function, put

TRACE_LEAVE_FN()

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:

main()
{
    try
    {
        run program here
    }

    catch(...)
    {
        cout << "Unhandled Exception!" << endl;
        CallStackTrace::Dump();
    }
}

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.

Discuss this article in the forums


Date this article was posted to GameDev.net: 10/22/2002
(Note that this date does not necessarily correspond to the date the article was written)

See Also:
Sweet Snippets

© 1999-2011 Gamedev.net. All rights reserved. Terms of Use Privacy Policy
Comments? Questions? Feedback? Click here!