4

What's the best way to implement an exception stack trace?

I found some kind of a solution using uncaught_exception() but it requires to add some code to every function.

I need something working on gcc under linux and windows

f4.
  • 53
  • 1
  • 3
  • What sort of output do you want to see? –  Jan 14 '10 at 13:53
  • Dupe: http://stackoverflow.com/questions/77005/how-to-generate-a-stacktrace-when-my-gcc-c-app-crashes – Daniel Earwicker Jan 14 '10 at 14:00
  • this is not the same question. I don't want a stacktrace when my app crashes, I want a stacktrace attached to my exceptions, much like e.printStackTrace(); in Java – f4. Jan 14 '10 at 14:05
  • 4
    Again, you are going into wrong direction with this. Don't try to replicate Java exceptions in C++. The languages are different. Take a look at boost::exception library though. – Nikolai Fetissov Jan 14 '10 at 14:10
  • 2
    actually i know very few of Java and don't intend to mimic it, i just found usefull being able to print where an exception originated from and what it went through ... for debugging purpose – f4. Jan 14 '10 at 14:26

3 Answers3

4

I don't think there's a cross-platform way to do it. On windows, look at the StackWalk method; on linux, man backtrace. This will get the information; it's up to you to format it.

Anne
  • 480
  • 5
  • 14
4

I'm not sure that a reliable cross-platform method for unwinding the stack exists.

All the platforms/architectures that I've worked on have offered a way to walk the stack when an exception occurs and match addresses to function names. None of these are portable, but the reporting framework can written to be portable with the actual stack walking code remaining platform-specific (StackWalk on Windows or backtrace on Linux).

You might take a look at the libunwind project. I've never used or looked into this myself, so it may not be what you are looking for.

jschmier
  • 15,458
  • 6
  • 54
  • 72
2

I implemented some code that generates the current stack trace as a string; take a look at the GetStackTrace() function that starts at line 1220 of this file if you are interested. The function works under Linux, MacOS/X, and Windows (note that I borrowed the Windows implementation from here, and that it takes an incredible amount of code to implement this feature under Windows.... bleah)

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234