{"id":17931453,"url":"https://github.com/jeremy-rifkin/cpptrace","last_synced_at":"2025-05-14T23:02:13.130Z","repository":{"id":178082932,"uuid":"661114227","full_name":"jeremy-rifkin/cpptrace","owner":"jeremy-rifkin","description":"Simple, portable, and self-contained stacktrace library for C++11 and newer","archived":false,"fork":false,"pushed_at":"2025-05-14T01:48:56.000Z","size":2946,"stargazers_count":948,"open_issues_count":11,"forks_count":106,"subscribers_count":13,"default_branch":"main","last_synced_at":"2025-05-14T02:34:52.588Z","etag":null,"topics":["backtrace","debugging","diagnostics","stacktrace"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jeremy-rifkin.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2023-07-01T20:46:47.000Z","updated_at":"2025-05-13T04:34:01.000Z","dependencies_parsed_at":"2023-11-18T16:23:57.666Z","dependency_job_id":"a55762b0-f4a0-493f-8813-87802a350d9e","html_url":"https://github.com/jeremy-rifkin/cpptrace","commit_stats":null,"previous_names":["jeremy-rifkin/cpptrace"],"tags_count":34,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeremy-rifkin%2Fcpptrace","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeremy-rifkin%2Fcpptrace/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeremy-rifkin%2Fcpptrace/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jeremy-rifkin%2Fcpptrace/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jeremy-rifkin","download_url":"https://codeload.github.com/jeremy-rifkin/cpptrace/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254243353,"owners_count":22038044,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["backtrace","debugging","diagnostics","stacktrace"],"created_at":"2024-10-28T21:21:53.313Z","updated_at":"2025-05-14T23:02:13.081Z","avatar_url":"https://github.com/jeremy-rifkin.png","language":"C++","readme":"# Cpptrace \u003c!-- omit in toc --\u003e\n\n[![CI](https://github.com/jeremy-rifkin/cpptrace/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/jeremy-rifkin/cpptrace/actions/workflows/ci.yml)\n[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=jeremy-rifkin_cpptrace\u0026metric=alert_status)](https://sonarcloud.io/summary/new_code?id=jeremy-rifkin_cpptrace)\n\u003cbr/\u003e\n[![Community Discord Link](https://img.shields.io/badge/Chat%20on%20the%20(very%20small)-Community%20Discord-blue?labelColor=2C3239\u0026color=7289DA\u0026style=flat\u0026logo=discord\u0026logoColor=959DA5)](https://discord.gg/frjaAZvqUZ)\n\u003cbr/\u003e\n[![Try on Compiler Explorer](https://img.shields.io/badge/-Compiler%20Explorer-brightgreen?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAQCAYAAAAmlE46AAAACXBIWXMAAACwAAAAsAEUaqtpAAABSElEQVQokYVTsU7DMBB9QMTCEJbOMLB5oF0tRfUPIPIJZctYJkZYu3WMxNL+ARUfQKpImcPgDYnsXWBgYQl61TkYyxI3Wef37j3fnQ/6vkcsikY9AbiWq0mpbevDBmLRqDEAA4CEHMADgFRwrwDmch6X2i73RCFVHvC/WCeCMAFpC2AFoPPu5x4md4rnAN4luS61nYWSgauNU8ydkr0bLTMYAoIYtWqxM4LtEumeERDtfUjlMDrp7L67iddyyJtOvUIu2rquVn4iiVSOKXYhiMSJWLwUJZLuQ2CWmVldV4MT11UmXgB8fr0dX3WP6VHMiVrscim6Da2mJxffzwSU2v6xWzSKmzQ4cUTOaCBTvWgU14xkzjhckKm/q3wnrRAcAhksxMZNAdxEf0fRKI6E8zqT1C0X28ccRpqAUltW5pu4sxv5Mb8B4AciE3bHMxz/+gAAAABJRU5ErkJggg==\u0026labelColor=2C3239\u0026style=flat\u0026label=Try+it+on\u0026color=30C452)](https://godbolt.org/z/c6TqTzqcf)\n\nCpptrace is a simple and portable C++ stacktrace library supporting C++11 and greater on Linux, macOS,\nand Windows including MinGW and Cygwin environments. The goal: Make stack traces simple for once.\n\nCpptrace also has a C API, docs [here](docs/c-api.md).\n\n## Table of Contents \u003c!-- omit in toc --\u003e\n\n- [30-Second Overview](#30-second-overview)\n  - [CMake FetchContent Usage](#cmake-fetchcontent-usage)\n- [Prerequisites](#prerequisites)\n- [Basic Usage](#basic-usage)\n- [`namespace cpptrace`](#namespace-cpptrace)\n  - [Stack Traces](#stack-traces)\n  - [Object Traces](#object-traces)\n  - [Raw Traces](#raw-traces)\n  - [Utilities](#utilities)\n  - [Formatting](#formatting)\n    - [Transforms](#transforms)\n  - [Configuration](#configuration)\n  - [Traces From All Exceptions](#traces-from-all-exceptions)\n    - [Removing the `CPPTRACE_` prefix](#removing-the-cpptrace_-prefix)\n    - [How it works](#how-it-works)\n    - [Performance](#performance)\n  - [Traced Exception Objects](#traced-exception-objects)\n    - [Wrapping std::exceptions](#wrapping-stdexceptions)\n    - [Exception handling with cpptrace exception objects](#exception-handling-with-cpptrace-exception-objects)\n  - [Terminate Handling](#terminate-handling)\n  - [Signal-Safe Tracing](#signal-safe-tracing)\n  - [Utility Types](#utility-types)\n  - [Headers](#headers)\n  - [Libdwarf Tuning](#libdwarf-tuning)\n  - [JIT Support](#jit-support)\n- [Supported Debug Formats](#supported-debug-formats)\n- [How to Include The Library](#how-to-include-the-library)\n  - [CMake FetchContent](#cmake-fetchcontent)\n  - [System-Wide Installation](#system-wide-installation)\n  - [Local User Installation](#local-user-installation)\n  - [Use Without CMake](#use-without-cmake)\n  - [Installation Without Package Managers or FetchContent](#installation-without-package-managers-or-fetchcontent)\n  - [Package Managers](#package-managers)\n    - [Conan](#conan)\n    - [Vcpkg](#vcpkg)\n- [Platform Logistics](#platform-logistics)\n  - [Windows](#windows)\n  - [macOS](#macos)\n- [Library Back-Ends](#library-back-ends)\n  - [Summary of Library Configurations](#summary-of-library-configurations)\n- [Testing Methodology](#testing-methodology)\n- [Notes About the Library](#notes-about-the-library)\n- [FAQ](#faq)\n  - [What about C++23 `\u003cstacktrace\u003e`?](#what-about-c23-stacktrace)\n  - [What does cpptrace have over other C++ stacktrace libraries?](#what-does-cpptrace-have-over-other-c-stacktrace-libraries)\n  - [I'm getting undefined standard library symbols like `std::__1::basic_string` on MacOS](#im-getting-undefined-standard-library-symbols-like-std__1basic_string-on-macos)\n- [Contributing](#contributing)\n- [License](#license)\n\n# 30-Second Overview\n\nGenerating stack traces is as easy as:\n\n```cpp\n#include \u003ccpptrace/cpptrace.hpp\u003e\n\nvoid trace() {\n    cpptrace::generate_trace().print();\n}\n```\n\n![Demo](res/demo.png)\n\nCpptrace can also retrieve function inlining information on optimized release builds:\n\n![Inlining](res/inlining.png)\n\nCpptrace provides access to resolved stack traces as well as lightweight raw traces (just addresses) that can be\nresolved later:\n\n```cpp\nconst auto raw_trace = cpptrace::generate_raw_trace();\n// then later\nraw_trace.resolve().print();\n```\n\nCpptrace provides a way to produce stack traces on arbitrary exceptions. More information on this system\n[below](#traces-from-all-exceptions).\n```cpp\n#include \u003ccpptrace/from_current.hpp\u003e\nvoid foo() {\n    throw std::runtime_error(\"foo failed\");\n}\nint main() {\n    CPPTRACE_TRY {\n        foo();\n    } CPPTRACE_CATCH(const std::exception\u0026 e) {\n        std::cerr\u003c\u003c\"Exception: \"\u003c\u003ce.what()\u003c\u003cstd::endl;\n        cpptrace::from_current_exception().print();\n    }\n}\n```\n\n![from_current](res/from_current.png)\n\nThere are a few extraneous frames at the top of the stack corresponding to internals of exception handling in the\nstandard library. These are a small price to pay for stack traces on all exceptions.\n\nCpptrace also provides a handful of traced exception objects that store stack traces when thrown. This is useful when\nthe exceptions might not be caught by `CPPTRACE_CATCH`:\n```cpp\n#include \u003ccpptrace/cpptrace.hpp\u003e\n\nvoid trace() {\n    throw cpptrace::logic_error(\"This wasn't supposed to happen!\");\n}\n```\n\n![Exception](res/exception.png)\n\nAdditional notable features:\n\n- Utilities for demangling\n- Utilities for catching `std::exception`s and wrapping them in traced exceptions\n- Signal-safe stack tracing\n- Source code snippets in traces\n- Extensive configuration options for [trace formatting](#formatting)\n\n![Snippets](res/snippets.png)\n\n## CMake FetchContent Usage\n\n```cmake\ninclude(FetchContent)\nFetchContent_Declare(\n  cpptrace\n  GIT_REPOSITORY https://github.com/jeremy-rifkin/cpptrace.git\n  GIT_TAG        v0.8.3 # \u003cHASH or TAG\u003e\n)\nFetchContent_MakeAvailable(cpptrace)\ntarget_link_libraries(your_target cpptrace::cpptrace)\n\n# Needed for shared library builds on windows:  copy cpptrace.dll to the same directory as the\n# executable for your_target\nif(WIN32)\n  add_custom_command(\n    TARGET your_target POST_BUILD\n    COMMAND ${CMAKE_COMMAND} -E copy_if_different\n    $\u003cTARGET_FILE:cpptrace::cpptrace\u003e\n    $\u003cTARGET_FILE_DIR:your_target\u003e\n  )\nendif()\n```\n\nBe sure to configure with `-DCMAKE_BUILD_TYPE=Debug` or `-DCMAKE_BUILD_TYPE=RelWithDebInfo` for symbols and line\ninformation.\n\nOn macOS it is recommended to generate a `.dSYM` file, see [Platform Logistics](#platform-logistics) below.\n\nFor other ways to use the library, such as through package managers, a system-wide installation, or on a platform\nwithout internet access see [How to Include The Library](#how-to-include-the-library) below.\n\n# Prerequisites\n\n\u003e [!IMPORTANT]\n\u003e Debug info (`-g`/`/Z7`/`/Zi`/`/DEBUG`/`-DBUILD_TYPE=Debug`/`-DBUILD_TYPE=RelWithDebInfo`) is required for complete\n\u003e trace information.\n\n# Basic Usage\n\n`cpptrace::generate_trace()` can be used to generate a `stacktrace` object at the current call site. Resolved frames can\nbe accessed from this object with `.frames` and the trace can be printed with `.print()`. Cpptrace also provides a\nmethod to get light-weight raw traces with `cpptrace::generate_raw_trace()`, which are just vectors of program counters,\nwhich can be resolved at a later time.\n\n# `namespace cpptrace`\n\nAll functions are thread-safe unless otherwise noted.\n\n## Stack Traces\n\nThe core resolved stack trace object. Generate a trace with `cpptrace::generate_trace()` or\n`cpptrace::stacktrace::current()`. On top of a set of helper functions `struct stacktrace` allows\ndirect access to frames as well as iterators.\n\n`cpptrace::stacktrace::print` can be used to print a stacktrace. `cpptrace::stacktrace::print_with_snippets` can be used\nto print a stack trace with source code snippets.\n\n```cpp\nnamespace cpptrace {\n    // Some type sufficient for an instruction pointer, currently always an alias to std::uintptr_t\n    using frame_ptr = std::uintptr_t;\n\n    struct stacktrace_frame {\n        frame_ptr raw_address; // address in memory\n        frame_ptr object_address; // address in the object file\n        // nullable\u003cT\u003e represents a nullable integer. More docs later.\n        nullable\u003cstd::uint32_t\u003e line;\n        nullable\u003cstd::uint32_t\u003e column;\n        std::string filename;\n        std::string symbol;\n        bool is_inline;\n        bool operator==(const stacktrace_frame\u0026 other) const;\n        bool operator!=(const stacktrace_frame\u0026 other) const;\n        object_frame get_object_info() const; // object_address is stored but if the object_path is needed this can be used\n        std::string to_string() const;\n        /* operator\u003c\u003c(ostream, ..) and std::format support exist for this object */\n    };\n\n    struct stacktrace {\n        std::vector\u003cstacktrace_frame\u003e frames;\n        // here as a drop-in for std::stacktrace\n        static stacktrace current(std::size_t skip = 0);\n        static stacktrace current(std::size_t skip, std::size_t max_depth);\n        void print() const;\n        void print(std::ostream\u0026 stream) const;\n        void print(std::ostream\u0026 stream, bool color) const;\n        void print_with_snippets() const;\n        void print_with_snippets(std::ostream\u0026 stream) const;\n        void print_with_snippets(std::ostream\u0026 stream, bool color) const;\n        std::string to_string(bool color = false) const;\n        void clear();\n        bool empty() const noexcept;\n        /* operator\u003c\u003c(ostream, ..), std::format support, and iterators exist for this object */\n    };\n\n    stacktrace generate_trace(std::size_t skip = 0);\n    stacktrace generate_trace(std::size_t skip, std::size_t max_depth);\n}\n```\n\n## Object Traces\n\nObject traces contain the most basic information needed to construct a stack trace outside the currently running\nexecutable. It contains the raw address, the address in the binary (ASLR and the object file's memory space and whatnot\nis resolved), and the path to the object the instruction pointer is located in.\n\n```cpp\nnamespace cpptrace {\n    struct object_frame {\n        std::string object_path;\n        frame_ptr raw_address;\n        frame_ptr object_address;\n    };\n\n    struct object_trace {\n        std::vector\u003cobject_frame\u003e frames;\n        static object_trace current(std::size_t skip = 0);\n        static object_trace current(std::size_t skip, std::size_t max_depth);\n        stacktrace resolve() const;\n        void clear();\n        bool empty() const noexcept;\n        /* iterators exist for this object */\n    };\n\n    object_trace generate_object_trace(std::size_t skip = 0);\n    object_trace generate_object_trace(std::size_t skip, std::size_t max_depth);\n}\n```\n\n## Raw Traces\n\nRaw trace access: A vector of program counters. These are ideal for fast and cheap traces you want to resolve later.\n\nNote it is important executables and shared libraries in memory aren't somehow unmapped otherwise libdl calls (and\n`GetModuleFileName` in windows) will fail to figure out where the program counter corresponds to.\n\n```cpp\nnamespace cpptrace {\n    struct raw_trace {\n        std::vector\u003cframe_ptr\u003e frames;\n        static raw_trace current(std::size_t skip = 0);\n        static raw_trace current(std::size_t skip, std::size_t max_depth);\n        object_trace resolve_object_trace() const;\n        stacktrace resolve() const;\n        void clear();\n        bool empty() const noexcept;\n        /* iterators exist for this object */\n    };\n\n    raw_trace generate_raw_trace(std::size_t skip = 0);\n    raw_trace generate_raw_trace(std::size_t skip, std::size_t max_depth);\n}\n```\n\n## Utilities\n\n`cpptrace::demangle` provides a helper function for name demangling, since it has to implement that helper internally\nanyways.\n\n`cpptrace::get_snippet` gets a text snippet, if possible, from for the given source file for +/- `context_size` lines\naround `line`.\n\n`cpptrace::isatty` and the fileno definitions are useful for deciding whether to use color when printing stack traces.\n\n`cpptrace::register_terminate_handler()` is a helper function to set a custom `std::terminate` handler that prints a\nstack trace from a cpptrace exception (more info below) and otherwise behaves like the normal terminate handler.\n\n```cpp\nnamespace cpptrace {\n    std::string demangle(const std::string\u0026 name);\n    std::string get_snippet(\n        const std::string\u0026 path,\n        std::size_t line,\n        std::size_t context_size,\n        bool color = false\n    );\n    bool isatty(int fd);\n\n    extern const int stdin_fileno;\n    extern const int stderr_fileno;\n    extern const int stdout_fileno;\n\n    void register_terminate_handler();\n}\n```\n\n## Formatting\n\nCpptrace provides a configurable formatter for stack trace printing which supports some common options. Formatters are\nconfigured with a sort of builder pattern, e.g.:\n```cpp\nauto formatter = cpptrace::formatter{}\n    .header(\"Stack trace:\")\n    .addresses(cpptrace::formatter::address_mode::object)\n    .snippets(true);\n```\n\nThis API is available through the `\u003ccpptrace/formatting.hpp\u003e` header.\n\nSynopsis:\n```cpp\nnamespace cpptrace {\n    class formatter {\n        formatter\u0026 header(std::string);\n        enum class color_mode { always, none, automatic };\n        formatter\u0026 colors(color_mode);\n        enum class address_mode { raw, object, none };\n        formatter\u0026 addresses(address_mode);\n        enum class path_mode { full, basename };\n        formatter\u0026 paths(path_mode);\n        formatter\u0026 snippets(bool);\n        formatter\u0026 snippet_context(int);\n        formatter\u0026 columns(bool);\n        formatter\u0026 filtered_frame_placeholders(bool);\n        formatter\u0026 filter(std::function\u003cbool(const stacktrace_frame\u0026)\u003e);\n        formatter\u0026 transform(std::function\u003cstacktrace_frame(stacktrace_frame)\u003e);\n\n        std::string format(const stacktrace_frame\u0026) const;\n        std::string format(const stacktrace_frame\u0026, bool color) const;\n\n        std::string format(const stacktrace\u0026) const;\n        std::string format(const stacktrace\u0026, bool color) const;\n\n        void print(const stacktrace_frame\u0026) const;\n        void print(const stacktrace_frame\u0026, bool color) const;\n        void print(std::ostream\u0026, const stacktrace_frame\u0026) const;\n        void print(std::ostream\u0026, const stacktrace_frame\u0026, bool color) const;\n        void print(std::FILE*, const stacktrace_frame\u0026) const;\n        void print(std::FILE*, const stacktrace_frame\u0026, bool color) const;\n\n        void print(const stacktrace\u0026) const;\n        void print(const stacktrace\u0026, bool color) const;\n        void print(std::ostream\u0026, const stacktrace\u0026) const;\n        void print(std::ostream\u0026, const stacktrace\u0026, bool color) const;\n        void print(std::FILE*, const stacktrace\u0026) const;\n        void print(std::FILE*, const stacktrace\u0026, bool color) const;\n    };\n}\n```\n\nOptions:\n| Setting                       | Description                                                    | Default                                                                  |\n| ----------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------ |\n| `header`                      | Header line printed before the trace                           | `Stack trace (most recent call first):`                                  |\n| `colors`                      | Default color mode for the trace                               | `automatic`, which attempts to detect if the target stream is a terminal |\n| `addresses`                   | Raw addresses, object addresses, or no addresses               | `raw`                                                                    |\n| `paths`                       | Full paths or just filenames                                   | `full`                                                                   |\n| `snippets`                    | Whether to include source code snippets                        | `false`                                                                  |\n| `snippet_context`             | How many lines of source context to show in a snippet          | `2`                                                                      |\n| `columns`                     | Whether to include column numbers if present                   | `true`                                                                   |\n| `filtered_frame_placeholders` | Whether to still print filtered frames as just `#n (filtered)` | `true`                                                                   |\n| `filter`                      | A predicate to filter frames with                              | None                                                                     |\n| `transform`                   | A transformer which takes a stacktrace frame and modifies it   | None                                                                     |\n\nThe `automatic` color mode attempts to detect if a stream that may be attached to a terminal. As such, it will not use\ncolors for the `formatter::format` method and it may not be able to detect if some ostreams correspond to terminals or\nnot. For this reason, `formatter::format` and `formatter::print` methods have overloads taking a color parameter. This\ncolor parameter will override configured color mode.\n\nRecommended practice with formatters: It's generally preferable to create formatters objects that are long-lived rather\nthan to create them on the fly every time a trace needs to be formatted.\n\nCpptrace provides access to a formatter with default settings with `get_default_formatter`:\n```cpp\nnamespace cpptrace {\n    const formatter\u0026 get_default_formatter();\n}\n```\n\n### Transforms\n\nA transform function can be specified for the formatter. This function is called before the configured `filter` is\nchecked. For example:\n\n```cpp\nauto formatter = cpptrace::formatter{}\n    .transform([](cpptrace::stacktrace_frame frame) {\n        frame.symbol = replace_all(frame, \"std::__cxx11::\", \"std::\");\n        return frame;\n    });\n```\n\n## Configuration\n\n`cpptrace::absorb_trace_exceptions`: Configure whether the library silently absorbs internal exceptions and continues.\nDefault is true.\n\n`cpptrace::enable_inlined_call_resolution`: Configure whether the library will attempt to resolve inlined call\ninformation for release builds. Default is true.\n\n`cpptrace::experimental::set_cache_mode`: Control time-memory tradeoffs within the library. By default speed is\nprioritized. If using this function, set the cache mode at the very start of your program before any traces are\nperformed.\n\n```cpp\nnamespace cpptrace {\n    void absorb_trace_exceptions(bool absorb);\n    void enable_inlined_call_resolution(bool enable);\n\n    enum class cache_mode {\n        // Only minimal lookup tables\n        prioritize_memory,\n        // Build lookup tables but don't keep them around between trace calls\n        hybrid,\n        // Build lookup tables as needed\n        prioritize_speed\n    };\n\n    namespace experimental {\n        void set_cache_mode(cache_mode mode);\n    }\n}\n```\n\n## Traces From All Exceptions\n\nCpptrace provides `CPPTRACE_TRY` and `CPPTRACE_CATCH` macros that allow a stack trace to be collected from the current\nthrown exception object, with minimal or no overhead in the non-throwing path:\n\n```cpp\n#include \u003ccpptrace/from_current.hpp\u003e\n#include \u003ciostream\u003e\n\nvoid foo() {\n    throw std::runtime_error(\"foo failed\");\n}\nint main() {\n    CPPTRACE_TRY {\n        foo();\n    } CPPTRACE_CATCH(const std::exception\u0026 e) {\n        std::cerr\u003c\u003c\"Exception: \"\u003c\u003ce.what()\u003c\u003cstd::endl;\n        cpptrace::from_current_exception().print();\n    }\n}\n```\n\nThis functionality is entirely opt-in, to access this use `#include \u003ccpptrace/from_current.hpp\u003e`.\n\nAny declarator `catch` accepts works with `CPPTRACE_CATCH`, including `...`. This works with any thrown object, not just\n`std::exceptions`, it even works with `throw 0;`\n\n![from_current](res/from_current.png)\n\nThere are a few extraneous frames at the top of the stack corresponding to standard library exception handling\ninternals. These are a small price to pay for stack traces on all exceptions.\n\nAPI functions:\n- `cpptrace::raw_trace_from_current_exception`: Returns `const raw_trace\u0026` from the current exception.\n- `cpptrace::from_current_exception`: Returns a resolved `const stacktrace\u0026` from the current exception. Invalidates\n  references to traces returned by `cpptrace::raw_trace_from_current_exception`.\n\nThere is a performance tradeoff with this functionality: Either the try-block can be zero overhead in the\nnon-throwing path with potential expense in the throwing path, or the try-block can have very minimal overhead\nin the non-throwing path due to bookkeeping with guarantees about the expense of the throwing path. More details on\nthis tradeoff [below](#performance). Cpptrace provides macros for both sides of this tradeoff:\n- `CPPTRACE_TRY`/`CPPTRACE_CATCH`: Minimal overhead in the non-throwing path (one `mov` on x86, and this may be\n  optimized out if the compiler is able)\n- `CPPTRACE_TRYZ`/`CPPTRACE_CATCHZ`: Zero overhead in the non-throwing path, potential extra cost in the throwing path\n\nNote: It's important to not mix the `Z` variants with the non-`Z` variants.\n\nUnfortunately the try/catch macros are needed to insert some magic to perform a trace during the unwinding search phase.\nIn order to have multiple catch alternatives, either `CPPTRACE_CATCH_ALT` or a normal `catch` must be used:\n```cpp\nCPPTRACE_TRY {\n    foo();\n} CPPTRACE_CATCH(const std::exception\u0026) { // \u003c- First catch must be CPPTRACE_CATCH\n    // ...\n} CPPTRACE_CATCH_ALT(const std::exception\u0026) { // \u003c- Ok\n    // ...\n} catch(const std::exception\u0026) { // \u003c- Also Ok\n    // ...\n} CPPTRACE_CATCH(const std::exception\u0026) { // \u003c- Not Ok\n    // ...\n}\n```\n\nNote: The current exception is the exception most recently seen by a cpptrace try-catch macro block.\n\n```cpp\nCPPTRACE_TRY {\n    throw std::runtime_error(\"foo\");\n} CPPTRACE_CATCH(const std::exception\u0026 e) {\n    cpptrace::from_current_exception().print(); // the trace for std::runtime_error(\"foo\")\n    CPPTRACE_TRY {\n        throw std::runtime_error(\"bar\");\n    } CPPTRACE_CATCH(const std::exception\u0026 e) {\n        cpptrace::from_current_exception().print(); // the trace for std::runtime_error(\"bar\")\n    }\n    cpptrace::from_current_exception().print(); // the trace for std::runtime_error(\"bar\"), again\n}\n```\n\n### Removing the `CPPTRACE_` prefix\n\n`CPPTRACE_TRY` is a little cumbersome to type. To remove the `CPPTRACE_` prefix you can use the\n`CPPTRACE_UNPREFIXED_TRY_CATCH` cmake option or the `CPPTRACE_UNPREFIXED_TRY_CATCH` preprocessor definition:\n\n```cpp\nTRY {\n    foo();\n} CATCH(const std::exception\u0026 e) {\n    std::cerr\u003c\u003c\"Exception: \"\u003c\u003ce.what()\u003c\u003cstd::endl;\n    cpptrace::from_current_exception().print();\n}\n```\n\nThis is not done by default for macro safety/hygiene reasons. If you do not want `TRY`/`CATCH` macros defined, as they\nare common macro names, you can easily modify the following snippet to provide your own aliases:\n\n```cpp\n#define TRY CPPTRACE_TRY\n#define CATCH(param) CPPTRACE_CATCH(param)\n#define TRYZ CPPTRACE_TRYZ\n#define CATCHZ(param) CPPTRACE_CATCHZ(param)\n#define CATCH_ALT(param) CPPTRACE_CATCH_ALT(param)\n```\n\n### How it works\n\nC++ does not provide any language support for collecting stack traces when exceptions are thrown, however, exception\nhandling under both the Itanium ABI and by SEH (used to implement C++ exceptions on windows) involves unwinding the\nstack twice. The first unwind searches for an appropriate `catch` handler, the second actually unwinds the stack and\ncalls destructors. Since the stack remains intact during the search phase it's possible to collect a stack trace with\nlittle to no overhead when the `catch` is considered for matching the exception. The try/catch macros for cpptrace set\nup a special try/catch system that can collect a stack trace when considered during a search phase.\n\nN.b.: This mechanism is also discussed in [P2490R3][P2490R3].\n\n### Performance\n\nThe fundamental mechanism for this functionality is generating a trace when a catch block is considered during an\nexception handler search phase. Internally a lightweight raw trace is generated upon consideration, which is quite\nfast. This raw trace is only resolved when `cpptrace::from_current_exception` is called, or when the user manually\nresolves a trace from `cpptrace::raw_trace_from_current_exception`.\n\nIt's tricky, however, from the library's standpoint to check if the catch will end up matching. The library could simply\ngenerate a trace every time a `CPPTRACE_CATCH` is considered, however, in a deep nesting of catch's, e.g. as a result of\nrecusion, where a matching handler is not found quickly this could introduce a non-trivial cost in the throwing pat due\nto tracing the stack multiple times. Thus, there is a performance tradeoff between a little book keeping to prevent\nduplicate tracing or biting the bullet, so to speak, in the throwing path and unwinding multiple times.\n\n\u003e [!TIP]\n\u003e The choice between the `Z` and non-`Z` (zero-overhead and non-zero-overhead) variants of the exception handlers should\n\u003e not matter 99% of the time, however, both are provided in the rare case that it does.\n\u003e\n\u003e `CPPTRACE_TRY`/`CPPTRACE_CATCH` could only hurt performance if used in a hot loop where the compiler can't optimize\n\u003e away the internal bookkeeping, otherwise the bookkeeping should be completely negligible.\n\u003e\n\u003e `CPPTRACE_TRYZ`/`CPPTRACE_CATCHZ` could only hurt performance when there is an exceptionally deep nesting of exception\n\u003e handlers in a call stack before a matching handler.\n\nMore information on performance considerations with the zero-overhead variant:\n\nTracing the stack multiple times in throwing paths should not matter for the vast majority applications given that:\n1. Performance very rarely is critical in throwing paths and exceptions should be exceptionally rare\n2. Exception handling is not usually used in such a way that you could have a deep nesting of handlers before finding a\n   matching handler\n3. Most call stacks are fairly shallow\n\nTo put the scale of this performance consideration into perspective: In my benchmarking I have found generation of raw\ntraces to take on the order of `100ns` per frame. Thus, even if there were 100 non-matching handlers before a matching\nhandler in a 100-deep call stack the total time would stil be on the order of one millisecond.\n\nNonetheless, I chose a default bookkeeping behavior for `CPPTRACE_TRY`/`CPPTRACE_CATCH` since it is safer with better\nperformance guarantees for the most general possible set of users.\n\n## Traced Exception Objects\n\nCpptrace provides a handful of traced exception classes which automatically collect stack traces when thrown. These\nare useful when throwing exceptions that may not be caught by `CPPTRACE_CATCH`.\n\nThe base traced exception class is `cpptrace::exception` and cpptrace provides a handful of helper classes for working\nwith traced exceptions. These exceptions generate relatively lightweight raw traces and resolve symbols and line numbers\nlazily if and when requested.\n\nThese are provided both as a useful utility and as a reference implementation for traced exceptions.\n\nThe basic interface is:\n```cpp\nnamespace cpptrace {\n    class exception : public std::exception {\n    public:\n        virtual const char* what() const noexcept = 0; // The what string both the message and trace\n        virtual const char* message() const noexcept = 0;\n        virtual const stacktrace\u0026 trace() const noexcept = 0;\n    };\n}\n```\n\nThere are two ways to go about traced exception objects: Traces can be resolved eagerly or lazily. Cpptrace provides the\nbasic implementation of exceptions as lazy exceptions. I hate to have anything about the implementation exposed in the\ninterface or type system but this seems to be the best way to do this.\n\n```cpp\nnamespace cpptrace {\n    class lazy_exception : public exception {\n        // lazy_trace_holder is basically a std::variant\u003craw_trace, stacktrace\u003e, more docs later\n        mutable detail::lazy_trace_holder trace_holder;\n        mutable std::string what_string;\n    public:\n        explicit lazy_exception(\n            raw_trace\u0026\u0026 trace = detail::get_raw_trace_and_absorb()\n        ) noexcept : trace_holder(std::move(trace)) {}\n        const char* what() const noexcept override;\n        const char* message() const noexcept override;\n        const stacktrace\u0026 trace() const noexcept override;\n    };\n}\n```\n\n`cpptrace::lazy_exception` can be freely thrown or overridden. Generally `message()` is the only field to override.\n\nLastly cpptrace provides an exception class that takes a user-provided message, `cpptrace::exception_with_message`, as\nwell as a number of traced exception classes resembling `\u003cstdexcept\u003e`:\n\n```cpp\nnamespace cpptrace {\n    class exception_with_message : public lazy_exception {\n        mutable std::string user_message;\n    public:\n        explicit exception_with_message(\n            std::string\u0026\u0026 message_arg,\n            raw_trace\u0026\u0026 trace = detail::get_raw_trace_and_absorb()\n        ) noexcept : lazy_exception(std::move(trace)), user_message(std::move(message_arg)) {}\n        const char* message() const noexcept override;\n    };\n\n    // All stdexcept errors have analogs here. All but system_error have the constructor:\n    // explicit the_error(\n    //     std::string\u0026\u0026 message_arg,\n    //     raw_trace\u0026\u0026 trace = detail::get_raw_trace_and_absorb()\n    // ) noexcept\n    //     : exception_with_message(std::move(message_arg), std::move(trace)) {}\n    class logic_error      : public exception_with_message { ... };\n    class domain_error     : public exception_with_message { ... };\n    class invalid_argument : public exception_with_message { ... };\n    class length_error     : public exception_with_message { ... };\n    class out_of_range     : public exception_with_message { ... };\n    class runtime_error    : public exception_with_message { ... };\n    class range_error      : public exception_with_message { ... };\n    class overflow_error   : public exception_with_message { ... };\n    class underflow_error  : public exception_with_message { ... };\n    class system_error : public runtime_error {\n    public:\n        explicit system_error(\n            int error_code,\n            std::string\u0026\u0026 message_arg,\n            raw_trace\u0026\u0026 trace = detail::get_raw_trace_and_absorb()\n        ) noexcept;\n        const std::error_code\u0026 code() const noexcept;\n    };\n}\n```\n\n### Wrapping std::exceptions\n\n\u003e [!NOTE]\n\u003e This section is largely obsolete now that cpptrace provides a better mechanism for collecting\n\u003e [traces from exceptions](#traces-from-exceptions)\n\nCpptrace exceptions can provide great information for user-controlled exceptions. For non-cpptrace::exceptions that may\noriginate outside of code you control, e.g. the standard library, cpptrace provides some wrapper utilities that can\nrethrow these exceptions nested in traced cpptrace exceptions. The trace won't be perfect, the trace will start where\nthe wrapper caught it, but these utilities can provide good diagnostic information. Unfortunately this is the best\nsolution for this problem, as far as I know.\n\n```cpp\nstd::vector\u003cint\u003e foo = {1, 2, 3};\nCPPTRACE_WRAP_BLOCK(\n    foo.at(4) = 2;\n    foo.at(5)++;\n);\nstd::cout\u003c\u003cCPPTRACE_WRAP(foo.at(12))\u003c\u003cstd::endl;\n```\n\n### Exception handling with cpptrace exception objects\n\n\u003e [!NOTE]\n\u003e This section pertains to cpptrace traced exception objects and not the mechanism for collecting\n\u003e [traces from arbitrary exceptions](#traces-from-exceptions)\n\nWorking with cpptrace exceptions in your code:\n```cpp\ntry {\n    foo();\n} catch(cpptrace::exception\u0026 e) {\n    // Prints the exception info and stack trace, conditionally enabling color codes depending on\n    // whether stderr is a terminal\n    std::cerr \u003c\u003c \"Error: \" \u003c\u003c e.message() \u003c\u003c '\\n';\n    e.trace().print(std::cerr, cpptrace::isatty(cpptrace::stderr_fileno));\n} catch(std::exception\u0026 e) {\n    std::cerr \u003c\u003c \"Error: \" \u003c\u003c e.what() \u003c\u003c '\\n';\n}\n```\n\n## Terminate Handling\n\nCpptrace provides a custom `std::terminate` handler that prints stacktraces while otherwise behaving like the normal\n`std::terminate` handler. If a cpptrace exception object reaches `std::terminate` the trace from that exception is\nprinted, otherwise a stack trace is generated at the point of the terminate handler. Often `std::terminate` is called\ndirectly without unwinding so the trace is preserved.\n\nTo register this custom handler:\n\n```cpp\ncpptrace::register_terminate_handler();\n```\n\n## Signal-Safe Tracing\n\nStack traces from signal handlers can provide very helpful information for debugging application crashes, e.g. from\nSIGSEGV or SIGTRAP handlers. Signal handlers are really restrictive environments as your application could be\ninterrupted by a signal at any point, including in the middle of malloc or buffered IO or while holding a lock.\nDoing a stack trace in a signal handler is possible but it requires a lot of care. This is difficult to do correctly\nand most examples online do this incorrectly.\n\nCpptrace offers an API to walk the stack in a signal handler and produce a raw trace safely. The library also provides\nan interface for producing a object frame safely:\n\n```cpp\nnamespace cpptrace {\n    std::size_t safe_generate_raw_trace(frame_ptr* buffer, std::size_t size, std::size_t skip = 0);\n    std::size_t safe_generate_raw_trace(frame_ptr* buffer, std::size_t size, std::size_t skip, std::size_t max_depth);\n    struct safe_object_frame {\n        frame_ptr raw_address;\n        frame_ptr address_relative_to_object_start;\n        char object_path[CPPTRACE_PATH_MAX + 1];\n        object_frame resolve() const; // To be called outside a signal handler. Not signal safe.\n    };\n    void get_safe_object_frame(frame_ptr address, safe_object_frame* out);\n    bool can_signal_safe_unwind();\n    bool can_get_safe_object_frame();\n}\n```\n\nIt is not possible to resolve debug symbols safely in the process from a signal handler without heroic effort. In order\nto produce a full trace there are three options:\n1. Carefully save the object trace information to be resolved at a later time outside the signal handler\n2. Write the object trace information to a file to be resolved later\n3. Spawn a new process, communicate object trace information to that process, and have that process do the trace\n   resolution\n\nFor traces on segfaults, e.g., only options 2 and 3 are viable. For more information an implementation of approach 3,\nsee the comprehensive overview and demo at [signal-safe-tracing.md](docs/signal-safe-tracing.md).\n\n\u003e [!IMPORTANT]\n\u003e Currently signal-safe stack unwinding is only possible with `libunwind`, which must be\n\u003e [manually enabled](#library-back-ends). If signal-safe unwinding isn't supported, `safe_generate_raw_trace` will just\n\u003e produce an empty trace. `can_signal_safe_unwind` can be used to check for signal-safe unwinding support and\n\u003e `can_get_safe_object_frame` can be used to check `get_safe_object_frame` support. If object information can't be\n\u003e resolved in a signal-safe way then `get_safe_object_frame` will not populate fields beyond the `raw_address`.\n\n\u003e [!IMPORTANT]\n\u003e `_dl_find_object` is required for signal-safe stack tracing. This is a relatively recent addition to glibc, added in\n\u003e glibc 2.35.\n\n\u003e [!CAUTION]\n\u003e Calls to shared objects can be lazy-loaded where the first call to the shared object invokes non-signal-safe functions\n\u003e such as `malloc()`. To avoid this, call these routines in `main()` ahead of a signal handler to \"warm up\" the library.\n\n## Utility Types\n\nA couple utility types are used to provide the library with a good interface.\n\n`nullable\u003cT\u003e` is used for a nullable integer type. Internally the maximum value for `T` is used as a\nsentinel. `std::optional` would be used if this library weren't c++11. But, `nullable\u003cT\u003e` provides\nan `std::optional`-like interface and it's less heavy-duty for this use than an `std::optional`.\n\n`detail::lazy_trace_holder` is a utility type for `lazy_exception` used in place of an\n`std::variant\u003craw_trace, stacktrace\u003e`.\n\n```cpp\nnamespace cpptrace {\n    template\u003ctypename T, typename std::enable_if\u003cstd::is_integral\u003cT\u003e::value, int\u003e::type = 0\u003e\n    struct nullable {\n        T raw_value;\n        // all members are constexpr for c++17 and beyond, some are constexpr before c++17\n        nullable\u0026 operator=(T value)\n        bool has_value() const noexcept;\n        T\u0026 value() noexcept;\n        const T\u0026 value() const noexcept;\n        T value_or(T alternative) const noexcept;\n        void swap(nullable\u0026 other) noexcept;\n        void reset() noexcept;\n        bool operator==(const nullable\u0026 other) const noexcept;\n        bool operator!=(const nullable\u0026 other) const noexcept;\n        constexpr static T null_value() noexcept; // returns the raw null value\n        constexpr static nullable null() noexcept; // returns a null instance\n    };\n\n    namespace detail {\n        class lazy_trace_holder {\n            bool resolved;\n            union {\n                raw_trace trace;\n                stacktrace resolved_trace;\n            };\n        public:\n            // constructors\n            lazy_trace_holder() : trace() {}\n            explicit lazy_trace_holder(raw_trace\u0026\u0026 _trace);\n            explicit lazy_trace_holder(stacktrace\u0026\u0026 _resolved_trace);\n            // logistics\n            lazy_trace_holder(const lazy_trace_holder\u0026 other);\n            lazy_trace_holder(lazy_trace_holder\u0026\u0026 other) noexcept;\n            lazy_trace_holder\u0026 operator=(const lazy_trace_holder\u0026 other);\n            lazy_trace_holder\u0026 operator=(lazy_trace_holder\u0026\u0026 other) noexcept;\n            ~lazy_trace_holder();\n            // access\n            const raw_trace\u0026 get_raw_trace() const;\n            stacktrace\u0026 get_resolved_trace();\n            const stacktrace\u0026 get_resolved_trace() const; // throws if not already resolved\n        private:\n            void clear();\n        };\n    }\n}\n```\n\n## Headers\n\nCpptrace provides a handful of headers to make inclusion more minimal.\n| Header                      | Contents                                                                                                                                                                                              |\n| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `cpptrace/forward.hpp`      | `cpptrace::frame_ptr` and a few trace class forward declarations                                                                                                                                      |\n| `cpptrace/basic.hpp`        | Definitions for trace classes and the basic tracing APIs ([Stack Traces](#stack-traces), [Object Traces](#object-traces), [Raw Traces](#raw-traces), and [Signal-Safe Tracing](#signal-safe-tracing)) |\n| `cpptrace/exceptions.hpp`   | [Traced Exception Objects](#traced-exception-objects) and related utilities ([Wrapping std::exceptions](#wrapping-stdexceptions))                                                                     |\n| `cpptrace/from_current.hpp` | [Traces From All Exceptions](#traces-from-all-exceptions)                                                                                                                                             |\n| `cpptrace/io.hpp`           | `operator\u003c\u003c` overloads for `std::ostream` and `std::formatter`s                                                                                                                                       |\n| `cpptrace/formatting.hpp`   | Configurable formatter API                                                                                                                                                                            |\n| `cpptrace/utils.hpp`        | Utility functions, configuration functions, and terminate utilities ([Utilities](#utilities), [Configuration](#configuration), and [Terminate Handling](#terminate-handling))                         |\n| `cpptrace/version.hpp`      | Library version macros                                                                                                                                                                                |\n| `cpptrace/gdb_jit.hpp`      | Provides a special utility related to [JIT support](#jit-support)                                                                                                                                     |\n\nThe main cpptrace header is `cpptrace/cpptrace.hpp` which includes everything other than `from_current.hpp` and\n`version.hpp`.\n\n## Libdwarf Tuning\n\nFor extraordinarily large binaries (multiple gigabytes), cpptrace's internal caching can result in a lot of memory\nusage. Cpptrace provides some options to reduce memory usage in exchange for performance in memory-constrained\napplications.\n\nSynopsis:\n\n```cpp\nnamespace cpptrace {\n    namespace experimental {\n        void set_dwarf_resolver_line_table_cache_size(nullable\u003cstd::size_t\u003e max_entries);\n        void set_dwarf_resolver_disable_aranges(bool disable);\n    }\n}\n```\n\nExplanation:\n- `set_dwarf_resolver_line_table_cache_size` can be used to set a limit to the cache size with evictions done LRU.\n  Cpptrace loads and caches line tables for dwarf compile units. These can take a lot of space for large binaries with\n  lots of debug info. Passing `nullable\u003cstd::size_t\u003e::null()` will disable the cache size (which is the default\n  behavior).\n- `set_dwarf_resolver_disable_aranges` can be used to disable use of dwarf `.debug_aranges`, an accelerated range lookup\n  table for compile units emitted by many compilers. Cpptrace uses these by default if they are present since they can\n  speed up resolution, however, they can also result in significant memory usage.\n\n## JIT Support\n\nCpptrace has support for resolving symbols from frames in JIT-compiled code. To do this, cpptrace relies on in-memory\nobject files (elf on linux or mach-o on mac) that contain symbol tables and dwarf debug information. The main reason for\nthis is many JIT implementations already produce these for debugger support.\n\nThese in-memory object files must be set up in such a way that the symbol table and debug symbol addresses match the\nrun-time addresses of the JIT code.\n\nThe basic interface for informing cpptrace about these in-memory object files is as follows:\n\n```cpp\nnamespace cpptrace {\n    void register_jit_object(const char*, std::size_t);\n    void unregister_jit_object(const char*);\n    void clear_all_jit_objects();\n}\n```\n\nMany JIT implementations follow the GDB [JIT Compilation Interface][jitci] so that JIT code can be debugged. The\ninterface, at a high level, entails adding in-memory object files to a linked list of object files that GDB and other\ndebuggers can reference (stored in the `__jit_debug_descriptor`). Cpptrace provides, as a utility, a mechanism for\nloading all in-memory object files present in the `__jit_debug_descriptor` linked list via `\u003ccpptrace/gdb_jit.hpp\u003e`:\n\n```cpp\nnamespace cpptrace {\n    namespace experimental {\n        void register_jit_objects_from_gdb_jit_interface();\n    }\n}\n```\n\nNote: Your program must be able to link against a global C symbol `__jit_debug_descriptor`.\n\nNote: Calling `cpptrace::experimental::register_jit_objects_from_gdb_jit_interface` clears all jit objects previously\nregistered with cpptrace.\n\n\n[jitci]: https://sourceware.org/gdb/current/onlinedocs/gdb.html/JIT-Interface.html\n\n# Supported Debug Formats\n\n| Format                       | Supported |\n| ---------------------------- | --------- |\n| DWARF in binary              | ✔️      |\n| GNU debug link               | ️️✔️  |\n| Split dwarf (debug fission)  | ✔️      |\n| DWARF in dSYM                | ✔️      |\n| DWARF via Mach-O debug map   | ✔️      |\n| Windows debug symbols in PDB | ✔️      |\n\nDWARF5 added DWARF package files. As far as I can tell no compiler implements these yet.\n\n# How to Include The Library\n\n## CMake FetchContent\n\nWith CMake FetchContent:\n\n```cmake\ninclude(FetchContent)\nFetchContent_Declare(\n  cpptrace\n  GIT_REPOSITORY https://github.com/jeremy-rifkin/cpptrace.git\n  GIT_TAG        v0.8.3 # \u003cHASH or TAG\u003e\n)\nFetchContent_MakeAvailable(cpptrace)\ntarget_link_libraries(your_target cpptrace::cpptrace)\n```\n\nIt's as easy as that. Cpptrace will automatically configure itself for your system. Note: On windows and macos some\nextra work is required, see [Platform Logistics](#platform-logistics) below.\n\nBe sure to configure with `-DCMAKE_BUILD_TYPE=Debug` or `-DCMAKE_BUILD_TYPE=RelWithDebInfo` for symbols and line\ninformation.\n\n## System-Wide Installation\n\n```sh\ngit clone https://github.com/jeremy-rifkin/cpptrace.git\ngit checkout v0.8.3\nmkdir cpptrace/build\ncd cpptrace/build\ncmake .. -DCMAKE_BUILD_TYPE=Release\nmake -j\nsudo make install\n```\n\nUsing through cmake:\n```cmake\nfind_package(cpptrace REQUIRED)\ntarget_link_libraries(\u003cyour target\u003e cpptrace::cpptrace)\n```\nBe sure to configure with `-DCMAKE_BUILD_TYPE=Debug` or `-DCMAKE_BUILD_TYPE=RelWithDebInfo` for symbols and line\ninformation.\n\nOr compile with `-lcpptrace`:\n\n```sh\ng++ main.cpp -o main -g -Wall -lcpptrace\n./main\n```\n\n\u003e [!IMPORTANT]\n\u003e If you aren't using cmake and are linking statically you must manually specify `-DCPPTRACE_STATIC_DEFINE`.\n\nIf you get an error along the lines of\n```\nerror while loading shared libraries: libcpptrace.so: cannot open shared object file: No such file or directory\n```\nYou may have to run `sudo /sbin/ldconfig` to create any necessary links and update caches so the system can find\nlibcpptrace.so (I had to do this on Ubuntu). Only when installing system-wide. Usually your package manager does this for\nyou when installing new libraries.\n\n\u003e [!NOTE]\n\u003e Libdwarf requires a relatively new version of libdwarf. Sometimes a previously-installed system-wide libdwarf may\n\u003e cause issues due to being too old. Libdwarf 8 and newer is known to work.\n\n\u003cdetails\u003e\n    \u003csummary\u003eSystem-wide install on windows\u003c/summary\u003e\n\n```ps1\ngit clone https://github.com/jeremy-rifkin/cpptrace.git\ngit checkout v0.8.3\nmkdir cpptrace/build\ncd cpptrace/build\ncmake .. -DCMAKE_BUILD_TYPE=Release\nmsbuild cpptrace.sln\nmsbuild INSTALL.vcxproj\n```\n\nNote: You'll need to run as an administrator in a developer powershell, or use vcvarsall.bat distributed with visual\nstudio to get the correct environment variables set.\n\u003c/details\u003e\n\n## Local User Installation\n\nTo install just for the local user (or any custom prefix):\n\n```sh\ngit clone https://github.com/jeremy-rifkin/cpptrace.git\ngit checkout v0.8.3\nmkdir cpptrace/build\ncd cpptrace/build\ncmake .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=$HOME/wherever\nmake -j\nmake install\n```\n\nUsing through cmake:\n```cmake\nfind_package(cpptrace REQUIRED PATHS $ENV{HOME}/wherever)\ntarget_link_libraries(\u003cyour target\u003e cpptrace::cpptrace)\n```\n\nUsing manually:\n```\ng++ main.cpp -o main -g -Wall -I$HOME/wherever/include -L$HOME/wherever/lib -lcpptrace\n```\n\n\u003e [!IMPORTANT]\n\u003e If you aren't using cmake and are linking statically you must manually specify `-DCPPTRACE_STATIC_DEFINE`.\n\n## Use Without CMake\n\nTo use the library without cmake first follow the installation instructions at\n[System-Wide Installation](#system-wide-installation), [Local User Installation](#local-user-installation),\nor [Package Managers](#package-managers).\n\nIn addition to any include or library paths you'll need to specify to tell the compiler where cpptrace was installed.\nThe typical dependencies for cpptrace are:\n\n| Compiler                | Platform         | Dependencies                              |\n| ----------------------- | ---------------- | ----------------------------------------- |\n| gcc, clang, intel, etc. | Linux/macos/unix | `-lcpptrace -ldwarf -lz -lzstd -ldl`      |\n| gcc                     | Windows          | `-lcpptrace -ldbghelp -ldwarf -lz -lzstd` |\n| msvc                    | Windows          | `cpptrace.lib dbghelp.lib`                |\n| clang                   | Windows          | `-lcpptrace -ldbghelp`                    |\n\nNote: Newer libdwarf requires `-lzstd`, older libdwarf does not.\n\n\u003e [!IMPORTANT]\n\u003e If you are linking statically, you will additionally need to specify `-DCPPTRACE_STATIC_DEFINE`.\n\nDependencies may differ if different back-ends are manually selected.\n\n## Installation Without Package Managers or FetchContent\n\nSome users may prefer, or need to, to install cpptrace without package managers or fetchcontent (e.g. if their system\ndoes not have internet access). Below are instructions for how to install libdwarf and cpptrace.\n\n\u003cdetails\u003e\n    \u003csummary\u003eInstallation Without Package Managers or FetchContent\u003c/summary\u003e\n\nHere is an example for how to build cpptrace and libdwarf. `~/scratch/cpptrace-test` is used as a working directory and\nthe libraries are installed to `~/scratch/cpptrace-test/resources`.\n\n```sh\nmkdir -p ~/scratch/cpptrace-test/resources\n\ncd ~/scratch/cpptrace-test\ngit clone https://github.com/facebook/zstd.git\ncd zstd\ngit checkout 63779c798237346c2b245c546c40b72a5a5913fe\ncd build/cmake\nmkdir build\ncd build\ncmake .. -DCMAKE_INSTALL_PREFIX=~/scratch/cpptrace-test/resources -DZSTD_BUILD_PROGRAMS=On -DZSTD_BUILD_CONTRIB=On -DZSTD_BUILD_TESTS=On -DZSTD_BUILD_STATIC=On -DZSTD_BUILD_SHARED=On -DZSTD_LEGACY_SUPPORT=On\nmake -j\nmake install\n\ncd ~/scratch/cpptrace-test\ngit clone https://github.com/jeremy-rifkin/libdwarf-lite.git\ncd libdwarf-lite\ngit checkout fe09ca800b988e2ff21225ac5e7468ceade2a30e\nmkdir build\ncd build\ncmake .. -DPIC_ALWAYS=On -DBUILD_DWARFDUMP=Off -DCMAKE_PREFIX_PATH=~/scratch/cpptrace-test/resources -DCMAKE_INSTALL_PREFIX=~/scratch/cpptrace-test/resources\nmake -j\nmake install\n\ncd ~/scratch/cpptrace-test\ngit clone https://github.com/jeremy-rifkin/cpptrace.git\ncd cpptrace\ngit checkout v0.8.3\nmkdir build\ncd build\ncmake .. -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=On -DCPPTRACE_USE_EXTERNAL_LIBDWARF=On -DCMAKE_PREFIX_PATH=~/scratch/cpptrace-test/resources -DCMAKE_INSTALL_PREFIX=~/scratch/cpptrace-test/resources\nmake -j\nmake install\n```\n\nThe `~/scratch/cpptrace-test/resources` directory also serves as a bundle you can ship with all the installed files for\ncpptrace and its dependencies.\n\n\u003c/details\u003e\n\n## Package Managers\n\n### Conan\n\nCpptrace is available through conan at https://conan.io/center/recipes/cpptrace.\n```\n[requires]\ncpptrace/0.8.3\n[generators]\nCMakeDeps\nCMakeToolchain\n[layout]\ncmake_layout\n```\n```cmake\n# ...\nfind_package(cpptrace REQUIRED)\n# ...\ntarget_link_libraries(YOUR_TARGET cpptrace::cpptrace)\n```\n\n### Vcpkg\n\n```\nvcpkg install cpptrace\n```\n```cmake\nfind_package(cpptrace CONFIG REQUIRED)\ntarget_link_libraries(main PRIVATE cpptrace::cpptrace)\n```\n\n# Platform Logistics\n\nWindows and macOS require a little extra work to get everything in the right place.\n\n## Windows\n\nCopying the library `.dll` on Windows:\n\n```cmake\n# Copy the cpptrace.dll on windows to the same directory as the executable for your_target.\n# Not required if static linking.\nif(WIN32)\n  add_custom_command(\n    TARGET your_target POST_BUILD\n    COMMAND ${CMAKE_COMMAND} -E copy_if_different\n    $\u003cTARGET_FILE:cpptrace::cpptrace\u003e\n    $\u003cTARGET_FILE_DIR:your_target\u003e\n  )\nendif()\n```\n\n## macOS\n\nOn macOS, it is recommended to generate a `dSYM` file containing debug information for your program.\nThis is not required as cpptrace makes a good effort at finding and reading the debug information\nwithout this, but having a `dSYM` file is the most robust method.\n\nWhen using Xcode with CMake, this can be done with:\n\n```cmake\nset_target_properties(your_target PROPERTIES XCODE_ATTRIBUTE_DEBUG_INFORMATION_FORMAT \"dwarf-with-dsym\")\n```\n\nOutside of Xcode, this can be done with `dsymutil yourbinary`:\n\n```cmake\n# Create a .dSYM file on macOS\nif(APPLE)\n  add_custom_command(\n    TARGET your_target\n    POST_BUILD\n    COMMAND dsymutil $\u003cTARGET_FILE:your_target\u003e\n  )\nendif()\n```\n\n# Library Back-Ends\n\nCpptrace supports a number of back-ends to produce stack traces. Stack traces are produced in roughly three steps:\nUnwinding, symbol resolution, and demangling.\n\nThe library's CMake automatically configures itself for what your system supports. The ideal configuration is as\nfollows:\n\n| Platform | Unwinding                                               | Symbols            | Demangling           |\n| -------- | ------------------------------------------------------- | ------------------ | -------------------- |\n| Linux    | `_Unwind`                                               | libdwarf           | cxxabi.h             |\n| MacOS    | `_Unwind` for gcc, execinfo.h for clang and apple clang | libdwarf           | cxxabi.h             |\n| Windows  | `StackWalk64`                                           | dbghelp            | No demangling needed |\n| MinGW    | `StackWalk64`                                           | libdwarf + dbghelp | cxxabi.h             |\n\nSupport for these back-ends is the main development focus and they should work well. If you want to use a different\nback-end such as addr2line, for example, you can configure the library to do so.\n\n**Unwinding**\n\n| Library       | CMake config                     | Platforms                    | Info                                                                                                                                                                                                                 |\n| ------------- | -------------------------------- | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| libgcc unwind | `CPPTRACE_UNWIND_WITH_UNWIND`    | linux, macos, mingw          | Frames are captured with libgcc's `_Unwind_Backtrace`, which currently produces the most accurate stack traces on gcc/clang/mingw. Libgcc is often linked by default, and llvm has something equivalent.             |\n| execinfo.h    | `CPPTRACE_UNWIND_WITH_EXECINFO`  | linux, macos                 | Frames are captured with `execinfo.h`'s `backtrace`, part of libc on linux/unix systems.                                                                                                                             |\n| winapi        | `CPPTRACE_UNWIND_WITH_WINAPI`    | windows, mingw               | Frames are captured with `CaptureStackBackTrace`.                                                                                                                                                                    |\n| dbghelp       | `CPPTRACE_UNWIND_WITH_DBGHELP`   | windows, mingw               | Frames are captured with `StackWalk64`.                                                                                                                                                                              |\n| libunwind     | `CPPTRACE_UNWIND_WITH_LIBUNWIND` | linux, macos, windows, mingw | Frames are captured with [libunwind](https://github.com/libunwind/libunwind). **Note:** This is the only back-end that requires a library to be installed by the user, and a `CMAKE_PREFIX_PATH` may also be needed. |\n| N/A           | `CPPTRACE_UNWIND_WITH_NOTHING`   | all                          | Unwinding is not done, stack traces will be empty.                                                                                                                                                                   |\n\nSome back-ends (execinfo and `CaptureStackBackTrace`) require a fixed buffer has to be created to read addresses into\nwhile unwinding. By default the buffer can hold addresses for 400 frames (beyond the `skip` frames). This is\nconfigurable with `CPPTRACE_HARD_MAX_FRAMES`.\n\n**Symbol resolution**\n\n| Library      | CMake config                             | Platforms             | Info                                                                                                                                                                                         |\n| ------------ | ---------------------------------------- | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| libdwarf     | `CPPTRACE_GET_SYMBOLS_WITH_LIBDWARF`     | linux, macos, mingw   | Libdwarf is the preferred method for symbol resolution for cpptrace. Cpptrace will get it via FetchContent or find_package depending on `CPPTRACE_USE_EXTERNAL_LIBDWARF`.                    |\n| dbghelp      | `CPPTRACE_GET_SYMBOLS_WITH_DBGHELP`      | windows               | Dbghelp.h is the preferred method for symbol resolution on windows under msvc/clang and is supported on all windows machines.                                                                |\n| libbacktrace | `CPPTRACE_GET_SYMBOLS_WITH_LIBBACKTRACE` | linux, macos*, mingw* | Libbacktrace is already installed on most systems or available through the compiler directly. For clang you must specify the absolute path to `backtrace.h` using `CPPTRACE_BACKTRACE_PATH`. |\n| addr2line    | `CPPTRACE_GET_SYMBOLS_WITH_ADDR2LINE`    | linux, macos, mingw   | Symbols are resolved by invoking `addr2line` (or `atos` on mac) via `fork()` (on linux/unix, and `popen` under mingw).                                                                       |\n| libdl        | `CPPTRACE_GET_SYMBOLS_WITH_LIBDL`        | linux, macos          | Libdl uses dynamic export information. Compiling with `-rdynamic` is needed for symbol information to be retrievable. Line numbers won't be retrievable.                                     |\n| N/A          | `CPPTRACE_GET_SYMBOLS_WITH_NOTHING`      | all                   | No attempt is made to resolve symbols.                                                                                                                                                       |\n\n*: Requires installation\n\nOne back-end should be used. For MinGW `CPPTRACE_GET_SYMBOLS_WITH_LIBDWARF` and `CPPTRACE_GET_SYMBOLS_WITH_DBGHELP` can\nbe used in conjunction.\n\nNote for addr2line: By default cmake will resolve an absolute path to addr2line to bake into the library. This path can\nbe configured with `CPPTRACE_ADDR2LINE_PATH`, or `CPPTRACE_ADDR2LINE_SEARCH_SYSTEM_PATH` can be used to have the library\nsearch the system path for `addr2line` at runtime. This is not the default to prevent against path injection attacks.\n\n**Demangling**\n\nLastly, depending on other back-ends used a demangler back-end may be needed.\n\n| Library   | CMake config                     | Platforms           | Info                                                                               |\n| --------- | -------------------------------- | ------------------- | ---------------------------------------------------------------------------------- |\n| cxxabi.h  | `CPPTRACE_DEMANGLE_WITH_CXXABI`  | Linux, macos, mingw | Should be available everywhere other than [msvc](https://godbolt.org/z/93ca9rcdz). |\n| dbghelp.h | `CPPTRACE_DEMANGLE_WITH_WINAPI`  | Windows             | Demangle with `UnDecorateSymbolName`.                                              |\n| N/A       | `CPPTRACE_DEMANGLE_WITH_NOTHING` | all                 | Don't attempt to do anything beyond what the symbol resolution back-end does.      |\n\n**More?**\n\nThere are plenty more libraries that can be used for unwinding, parsing debug information, and demangling. In the future\nmore back-ends can be added. Ideally this library can \"just work\" on systems, without additional installation work.\n\n## Summary of Library Configurations\n\nSummary of all library configuration options:\n\nBack-ends:\n- `CPPTRACE_GET_SYMBOLS_WITH_LIBDWARF=On/Off`\n- `CPPTRACE_GET_SYMBOLS_WITH_DBGHELP=On/Off`\n- `CPPTRACE_GET_SYMBOLS_WITH_LIBBACKTRACE=On/Off`\n- `CPPTRACE_GET_SYMBOLS_WITH_ADDR2LINE=On/Off`\n- `CPPTRACE_GET_SYMBOLS_WITH_LIBDL=On/Off`\n- `CPPTRACE_GET_SYMBOLS_WITH_NOTHING=On/Off`\n- `CPPTRACE_UNWIND_WITH_UNWIND=On/Off`\n- `CPPTRACE_UNWIND_WITH_LIBUNWIND=On/Off`\n- `CPPTRACE_UNWIND_WITH_EXECINFO=On/Off`\n- `CPPTRACE_UNWIND_WITH_WINAPI=On/Off`\n- `CPPTRACE_UNWIND_WITH_DBGHELP=On/Off`\n- `CPPTRACE_UNWIND_WITH_NOTHING=On/Off`\n- `CPPTRACE_DEMANGLE_WITH_CXXABI=On/Off`\n- `CPPTRACE_DEMANGLE_WITH_WINAPI=On/Off`\n- `CPPTRACE_DEMANGLE_WITH_NOTHING=On/Off`\n\nBack-end configuration:\n- `CPPTRACE_BACKTRACE_PATH=\u003cstring\u003e`: Path to libbacktrace backtrace.h, needed when compiling with clang/\n- `CPPTRACE_HARD_MAX_FRAMES=\u003cnumber\u003e`: Some back-ends write to a fixed-size buffer. This is the size of that buffer.\n  Default is `400`.\n- `CPPTRACE_ADDR2LINE_PATH=\u003cstring\u003e`: Specify the absolute path to the addr2line binary for cpptrace to invoke. By\n  default the config script will search for a binary and use that absolute path (this is to prevent against path\n  injection).\n- `CPPTRACE_ADDR2LINE_SEARCH_SYSTEM_PATH=On/Off`: Specifies whether cpptrace should let the system search the PATH\n  environment variable directories for the binary.\n\nOther useful configurations:\n- `CPPTRACE_BUILD_SHARED=On/Off`: Override for `BUILD_SHARED_LIBS`.\n- `CPPTRACE_INCLUDES_WITH_SYSTEM=On/Off`: Marks cpptrace headers as `SYSTEM` which will hide any warnings that aren't\n  the fault of your project. Defaults to On.\n- `CPPTRACE_INSTALL_CMAKEDIR`: Override for the installation path for the cmake configs.\n- `CPPTRACE_USE_EXTERNAL_LIBDWARF=On/Off`: Get libdwarf from `find_package` rather than `FetchContent`.\n- `CPPTRACE_POSITION_INDEPENDENT_CODE=On/Off`: Compile the library as a position independent code (PIE). Defaults to On.\n- `CPPTRACE_STD_FORMAT=On/Off`: Control inclusion of `\u003cformat\u003e` and provision of `std::formatter` specializations by\n  cpptrace.hpp. This can also be controlled with the macro `CPPTRACE_NO_STD_FORMAT`.\n\nTesting:\n- `CPPTRACE_BUILD_TESTING` Build small demo and test program\n- `CPPTRACE_BUILD_TEST_RDYNAMIC` Use `-rdynamic` when compiling the test program\n\n# Testing Methodology\n\nCpptrace currently uses integration and functional testing, building and running under every combination of back-end\noptions. The implementation is based on [github actions matrices][1] and driven by python scripts located in the\n[`ci/`](ci/) folder. Testing used to be done by github actions matrices directly, however, launching hundreds of two\nsecond jobs was extremely inefficient. Test outputs are compared against expected outputs located in\n[`test/expected/`](test/expected/). Stack trace addresses may point to the address after an instruction depending on the\nunwinding back-end, and the python script will check for an exact or near-match accordingly.\n\n[1]: https://docs.github.com/en/actions/using-jobs/using-a-matrix-for-your-jobs\n\n# Notes About the Library\n\nFor the most part I'm happy with the state of the library. But I'm sure that there is room for improvement and issues\nwill exist. If you encounter any issue, please let me know! If you find any pain-points in the library, please let me\nknow that too.\n\nA note about performance: For handling of DWARF symbols there is a lot of room to explore for performance optimizations\nand time-memory tradeoffs. If you find the current implementation is either slow or using too much memory, I'd be happy\nto explore some of these options.\n\nA couple things I'd like to improve in the future:\n- On Windows when collecting symbols with dbghelp (msvc/clang) parameter types are almost perfect but due to limitations\n  in dbghelp the library cannot accurately show const and volatile qualifiers or rvalue references (these appear as\n  pointers).\n\n# FAQ\n\n## What about C++23 `\u003cstacktrace\u003e`?\n\nSome day C++23's `\u003cstacktrace\u003e` will be ubiquitous. And maybe one day the msvc implementation will be acceptable.\nThe original motivation for cpptrace was to support projects using older C++ standards and as the library has grown its\nfunctionality has extended beyond the standard library's implementation.\n\nCpptrace provides functionality beyond what the standard library provides and what implementations provide, such as:\n- Walking inlined function calls\n- Providing a lightweight interface for \"raw traces\"\n- Resolving function parameter types\n- Providing traced exception objects\n- Providing an API for signal-safe stacktrace generation\n- Providing a way to retrieve stack traces from arbitrary exceptions, not just special cpptrace traced exception\n  objects. This is a feature coming to C++26, but cpptrace provides a solution for C++11.\n\n## What does cpptrace have over other C++ stacktrace libraries?\n\nOther C++ stacktrace libraries, such as boost stacktrace and backward-cpp, fall short when it comes to portability and\nease of use. In testing, I found neither to provide adaquate coverage of various environments. Even when they can be\nmade to work in an environment they require manual configuration from the end-user, possibly requiring manual\ninstallation of third-party dependencies. This is a highly undesirable burden to impose on users, especially when it is\nfor a software package which just provides diagnostics as opposed to core functionality. Additionally, cpptrace provides\nsupport for resolving inlined calls by default for DWARF symbols (boost does not do this, backward-cpp can do this but\nonly for some back-ends), better support for resolving full function signatures, and nicer API, among other features.\n\n## I'm getting undefined standard library symbols like `std::__1::basic_string` on MacOS\n\nIf you see a linker error along the lines of the following on MacOS then it's highly likely you are mixing standard\nlibrary ABIs.\n\n```\nUndefined symbols for architecture arm64:\n  \"std::__1::basic_string\u003cchar, std::__1::char_traits\u003cchar\u003e, std::__1::allocator\u003cchar\u003e \u003e::find(char, unsigned long) const\", referenced from:\n      cpptrace::detail::demangle(std::__1::basic_string\u003cchar, std::__1::char_traits\u003cchar\u003e, std::__1::allocator\u003cchar\u003e \u003e const\u0026, bool) in libcpptrace.a(demangle_with_cxxabi.cpp.o)\n      cpptrace::detail::snippet_manager::build_line_table() in libcpptrace.a(snippet.cpp.o)\n```\n\nThis can happen when using apple clang to compile cpptrace and gcc to compile your code, or vice versa. The reason is\nthat apple clang defaults to libc++ and gcc defaults to libstdc++ and these two standard library implementations are not\nABI-compatible. To resolve this, ensure you are compiling both cpptrace and your code with the same standard library by\neither using the same compiler for both or using `-stdlib=libc++`/`-stdlib=libstdc++` to control which standard library\nis used.\n\n# Contributing\n\nI'm grateful for the help I've received with this library and I welcome contributions! For information on contributing\nplease refer to [CONTRIBUTING.md](./CONTRIBUTING.md).\n\n# License\n\nThis library is under the MIT license.\n\nCpptrace uses libdwarf on linux, macos, and mingw/cygwin unless configured to use something else. If this library is\nstatically linked with libdwarf then the library's binary will itself be LGPL.\n\n[P2490R3]: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p2490r3.html\n","funding_links":[],"categories":["Debug","C++","Diagnostics"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjeremy-rifkin%2Fcpptrace","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjeremy-rifkin%2Fcpptrace","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjeremy-rifkin%2Fcpptrace/lists"}