1

Possible Duplicate:
print call stack in C or C++

Often times when debugging code I need to figure out who is calling the function that I have placed a debug statement in. I know that __FUNCTION__ evaluates to the name of the current function, but is there something similar that will give me the name of the callee? Or maybe print out the call stack?

The information must be available. If I put in an assert or code that will segfault, I get a stack trace that shows the entire call stack. Where does the stack trace-printing code get that information?

If you are unable to produce a platform-agnostic solution, then something that will work on x86_64 Ubuntu 12.04 compiled with gcc will do. Bonus points for providing solutions for other platforms as well.

Community
  • 1
  • 1
Cory Klein
  • 51,188
  • 43
  • 183
  • 243

3 Answers3

1

This is OS-dependent.

On Linux and gcc, use backtrace(3). For Windows, see this SO question.

Community
  • 1
  • 1
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
0

The stack trace gets that information by walking the call stack looking for return addresses and pawing through the executable to find which function a return address returns to. Nothing portable there. No general way to find the caller. The best you can do is run under a debugger and set a breakpoint to trigger when the debug code fires.

Also, __FUNCTION__ is not part of Standard C++. Seems to me it's a GNU thing.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

It doesn't give you the name of the caller, but the intrinsic function _ReturnAddress() usually returns a pointer that points back to the caller.

user541686
  • 205,094
  • 128
  • 528
  • 886