Click here to Skip to main content
15,886,560 members
Articles / Programming Languages / C++
Tip/Trick

Printing Stack Traces

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
16 Mar 2019MIT 2.7K  
How to print stack traces

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.

C++
#include <iostream>
#include <future>
#define BOOST_STACKTRACE_GNU_SOURCE_NOT_REQUIRED
#include <boost/stacktrace.hpp>

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;
}

Program Output

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
This article was originally posted at https://vorbrodt.blog/2019/03/15/printing-stack-traces

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --