16

I have a program written in C that runs on Linux, MacOS and Windows. Is there a way I can call a function and generate a stack trace? This would be super-useful for me. Ideally I'd like to do it on all three platforms, but Linux is the most important. (Windows is being compiled via mingw.)

Thanks.

7

For example, in GCC and the GNU libc C library, you can use backtrace().

As @slugonamission suggests, Windows offers CaptureStackBackTrace() - thanks!

Other platforms may offer similar features.

(This is obviously a platform-dependent question.)

(On a related note, there also exist self-disassembly libraries.)

| improve this answer | |
6

I'm using this code to generate debug stack traces. It uses libunwind to get the stacktrace and libdwfl to read debug information.

It produces nice Java-like stack traces, with function names and source locations. eg.:

at c(stack_trace.c:95)
at b(stack_trace.c:100)
at a(stack_trace.c:105)
at main(stack_trace.c:110)

libunwind should work on Windows and Mac, but libdwfl is Linux and ELF specific.

| improve this answer | |
  • 1
    Thanks. I downloaded libunwind and it did not compile on my Mac. – vy32 Nov 7 '11 at 20:06
  • 1
    @vy32 you are right. It turns out they are both Linux specific. – Piotr Praszmo Nov 7 '11 at 20:36
  • Can we generate backtrace using libunwind when the program crash? – Pritesh Acharya Sep 5 '13 at 4:57
  • @PriteshAcharya Just print the stacktrace in SIGSEGV signal handler. Be careful with this code though. It's riddled with undefined behavior. – Piotr Praszmo Sep 5 '13 at 16:41
  • yea. I don't wanna get a new SIGSEGV inside the SIGSEGV handler. :D – Pritesh Acharya Sep 6 '13 at 5:08
1

Ian Lance Taylor's libbacktrace does this. It handles stack unwinding and provides support for DWARF debugging symbols.

https://github.com/ErwanLegrand/libbacktrace

It supports only ELF, though.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.