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:
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¶
Using vcpkg¶
For more, see the official documentation.
Related Topics¶
- Building C++ Projects with Bazel | C++那些事
- Debugging Bazel Builds with LLDB | C++那些事
- CMake Essentials in Practice | C++那些事
- Getting Started with the Conan C++ Package Manager | C++那些事
- C++ Insights Compile-Time Observation | C++那些事
- Interactive C++ in Jupyter Notebook | C++那些事
- C++ string to int | C++那些事
- GCC Compilation Flags Explained | C++那些事
- Debugging C++ Programs with GDB | C++那些事
- GDB Python Extension Debugging | C++那些事