Skip to content

Instantly share code, notes, and snippets.

@hbobenicio
Created July 17, 2025 19:34
Show Gist options
  • Save hbobenicio/70f93846e15abe09090354b942458dce to your computer and use it in GitHub Desktop.
Save hbobenicio/70f93846e15abe09090354b942458dce to your computer and use it in GitHub Desktop.
Simple stacktrace printing in C using libbacktrace
/**
* A simple demonstration of libbacktrace to print a stacktrace.
*
* bear -- gcc -O0 -g -o main main.c -lbacktrace && ./main
* bear -- clang -O0 -g -isystem /usr/lib/gcc/x86_64-linux-gnu/12/include/ -o main main.c -lbacktrace && ./main
*/
#include <stdio.h>
#include <backtrace.h>
typedef struct {
struct backtrace_state* state;
} StacktraceContext;
// global/static or thread local??
StacktraceContext stacktrace_ctx = {0};
void stacktrace_setup(void)
{
// The name of the executable
const char* filename = NULL;
// Non-zero if threaded
int threaded = 0;
backtrace_error_callback error_callback = NULL;
void* userdata = NULL;
stacktrace_ctx.state = backtrace_create_state(filename, threaded, error_callback, userdata);
}
void stacktrace_print(void)
{
int skip_frames = 0;
backtrace_print(stacktrace_ctx.state, skip_frames, stderr);
}
void bar()
{
stacktrace_print();
puts("It Works!");
}
void foo()
{
bar();
}
int main()
{
stacktrace_setup();
//TODO add signal handling
foo();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment