17.16 Stack traces

Printing a stack trace was traditionally seen as a feature of the debugging environment and thus only implemented in the debuggers (gdb etc.). However, they are also useful in production code, for use in two circumstances:

And in fact, printing a stack trace is part of the basic runtime system in programming languages such as Java (printStackTrace method), Python (print_exception method), Go (PrintStack function), and ISO C++ 23 (std::stacktrace class).

Gnulib provides a module ‘stack-trace’ with this feature: print_stack_trace () prints a stack trace of the current thread to standard error.

For it to work best, three requirements need to be met:

When these requirements are not met, the function print_stack_trace () either prints a stack trace without source file names and line numbers, or prints nothing at all.

Gnulib also provides a module ‘abort-debug’, that overrides the abort function so that it prints the stack trace of the current thread, before actually aborting. Thus, abort () remains the idiom of choice for signaling a fatal situation that requires developer attention: it is useful both in debugging environments and production code.

Note: While the original abort function is safe to call in signal handlers, the overridden abort function is not. In signal handlers, you will need to call the original abort function, by doing #undef abort first.