How to get a stack trace for C++ using gcc with line number information?

后端 未结 14 2025
长发绾君心
长发绾君心 2020-11-27 09:54

We use stack traces in proprietary assert like macro to catch developer mistakes - when error is caught, stack trace is printed.

I find gcc\'s pair

14条回答
  •  一向
    一向 (楼主)
    2020-11-27 10:35

    There is a robust discussion of essentially the same question at: How to generate a stacktrace when my gcc C++ app crashes. Many suggestions are provided, including lots of discussion about how to generate stack traces at run-time.

    My personal favorite answer from that thread was to enable core dumps which allows you to view the complete application state at the time of the crash (including function arguments, line numbers, and unmangled names). An additional benefit of this approach is that it not only works for asserts, but also for segmentation faults and unhandled exceptions.

    Different Linux shells use different commands to enable core dumps, but you can do it from within your application code with something like this...

    #include 
    ...
    struct rlimit core_limit = { RLIM_INFINITY, RLIM_INFINITY };
    assert( setrlimit( RLIMIT_CORE, &core_limit ) == 0 ); // enable core dumps for debug builds
    

    After a crash, run your favorite debugger to examine the program state.

    $ kdbg executable core
    

    Here's some sample output...

    alt text

    It is also possible to extract the stack trace from a core dump at the command line.

    $ ( CMDFILE=$(mktemp); echo "bt" >${CMDFILE}; gdb 2>/dev/null --batch -x ${CMDFILE} temp.exe core )
    Core was generated by `./temp.exe'.
    Program terminated with signal 6, Aborted.
    [New process 22857]
    #0  0x00007f4189be5fb5 in raise () from /lib/libc.so.6
    #0  0x00007f4189be5fb5 in raise () from /lib/libc.so.6
    #1  0x00007f4189be7bc3 in abort () from /lib/libc.so.6
    #2  0x00007f4189bdef09 in __assert_fail () from /lib/libc.so.6
    #3  0x00000000004007e8 in recursive (i=5) at ./demo1.cpp:18
    #4  0x00000000004007f3 in recursive (i=4) at ./demo1.cpp:19
    #5  0x00000000004007f3 in recursive (i=3) at ./demo1.cpp:19
    #6  0x00000000004007f3 in recursive (i=2) at ./demo1.cpp:19
    #7  0x00000000004007f3 in recursive (i=1) at ./demo1.cpp:19
    #8  0x00000000004007f3 in recursive (i=0) at ./demo1.cpp:19
    #9  0x0000000000400849 in main (argc=1, argv=0x7fff2483bd98) at ./demo1.cpp:26
    

提交回复
热议问题