This one will be short 🙂

If you want to add more diagnostic information to your programs make sure to check out Boost.Stacktrace library. With it you can capture and print current stack traces. It’s especially useful when combined with exception handling; it allows you to know right away where the exception originated from.

#include 
#include 
#define BOOST_STACKTRACE_GNU_SOURCE_NOT_REQUIRED
#include 

using namespace std;
using namespace boost::stacktrace;

void f1();
void f2();
void f3();

void f1() { f2(); }
void f2() { f3(); }
void f3() { cout << stacktrace() << endl << endl; }

int main(int argc, char** argv)
{
	f1();

	auto f = async(launch::async, []() { cout << stacktrace() << endl << endl; });
	f.get();

	return 1;
}

0# f3() in /Users/martin/stacktrace
1# f2() in /Users/martin/stacktrace
2# f1() in /Users/martin/stacktrace
3# main in /Users/martin/stacktrace

0# main::$_0::operator()() const in /Users/martin/stacktrace

1# void std::__1::__async_func<main::$_0>::__execute<>(std::__1::__tuple_indices<>) in /Users/martin/stacktrace

2# std::__1::__async_func<main::$_0>::operator()() in /Users/martin/stacktrace

3# std::__1::__async_assoc_state<void, std::__1::__async_func<main::$_0> >::__execute() in /Users/martin/stacktrace

4# void* std::__1::__thread_proxy<std::__1::tuple<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, void (std::__1::__async_assoc_state<void, std::__1::__async_func<main::$_0> >::*)(), std::__1::__async_assoc_state<void, std::__1::__async_func<main::$_0> >*> >(void*) in /Users/martin/stacktrace

5# _pthread_body in /usr/lib/system/libsystem_pthread.dylib

6# _pthread_start in /usr/lib/system/libsystem_pthread.dylib

Program output

One Reply to “Printing stack traces”

Leave a Reply to Roy BellinganCancel reply