Skip to content

Last updated:2026-10-12

The C++ dbg-macro Debugging Macro

Logging is an indispensable way of debugging in C++ development. Inspired by the dbg macro in Rust, dbg-macro provides a better macro function than printf and std::cout. Its main features are as follows:

  • Beautiful colored output (colors are automatically disabled when the output is not an interactive terminal)
  • C++11 compatible and header-only
  • Supports printing both fundamental types and STL container types
  • Can print the file name, line number, function name, and the original expression

For example, the following code:

#include <vector>
#include <dbg.h>

// You can use "dbg(..)" in expressions:
int factorial(int n) {
  if (dbg(n <= 1)) {
    return dbg(1);
  } else {
    return dbg(n * factorial(n - 1));
  }
}

int main() {
  std::string message = "hello";
  dbg(message);  // [example.cpp:15 (main)] message = "hello" (std::string)

  const int a = 2;
  const int b = dbg(3 * a) + 1;  // [example.cpp:18 (main)] 3 * a = 6 (int)

  std::vector<int> numbers{b, 13, 42};
  dbg(numbers);  // [example.cpp:21 (main)] numbers = {7, 13, 42} (size: 3) (std::vector<int>)

  dbg("this line is executed");  // [example.cpp:23 (main)] this line is executed

  factorial(4);

  return 0;
}

The result looks like this:

68747470733a2f2f692e696d6775722e636f6d2f4e4845596b39412e706e67

Installation

git clone https://github.com/sharkdp/dbg-macro
sudo ln -s $(readlink -f dbg-macro/dbg.h) /usr/include/dbg.h

Now you can use dbg.h anywhere.

On Arch Linux

yay -S dbg-macro

Using vcpkg

vcpkg install dbg-macro

For more, see the official documentation.

Comments