StackTrace ≅

How to automatically generate a stacktrace when my program crashes - SO

Backward-cpp

Header only - a beautiful stack trace pretty printer for C++.

  • can be installed via meson or conan or directly

This one is very easy to setup
And well suited for VScode code runner one liner compiler command:

  • define a backend for stackunwiding
  • include backward.hpp if you are using the API directly
  • modify backward.cpp to use the same backend - if you want automated trace dump on SIGNAL
// backward-cpp/backward.hpp.cpp
#define BACKWARD_HAS_BFD 1    // uncomment this
# make sure the proper backend is available
$ apt-get install binutils-dev

All setup! Now compile with

# make sure the proper backend is available
$ g++/clang++ -lbfd + include backward-cpp/backward.hpp.cpp in the sources

Optionally add that in the place you are need to call the API directly (make sure the backend is the same)

// in main.cc
#define BACKWARD_HAS_BFD 1
#include <backward-cpp/backward.hpp>

This would be the .run config

"cpp": "cd $dir && g++-11 -g $fileName ~/DEV/cpp/backward-cpp/backward.cpp -o $fileNameWithoutExt -g -O0 -std=gnu++17 -Werror=return-type -g -pthread -lm -lpthread -lbfd -ldl -lcrypt -I $workspaceRoot -I ~/DEV/cpp  && $dir$fileNameWithoutExt",

And you will get this automatically caption

Cpptrace

A simple, portable, and self-contained C++ stacktrace library supporting C++11 and greater on Linux

  • can be installed via conan

caption

see also

Shortest implementation with glib

#include <stdio.h>
#include <execinfo.h>
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>


void handler(int sig) {
  void *array[10];
  size_t size;

  // get void*'s for all entries on the stack
  size = backtrace(array, 10);

  // print out all the frames to stderr
  fprintf(stderr, "Error: signal %d:\n", sig);
  backtrace_symbols_fd(array, size, STDERR_FILENO);
  exit(1);
}

void baz() {
 int *foo = (int*)-1; // make a bad pointer
  printf("%d\n", *foo);       // causes segfault
}

void bar() { baz(); }
void foo() { bar(); }


int main(int argc, char **argv) {
  signal(SIGSEGV, handler);   // install our handler
  foo(); // this will call foo, bar, and baz.  baz segfaults.
}
Written on December 8, 2022, Last update on October 17, 2024
debug-c++ stacktrace single-header codingame vscode