• Stars
    star
    2,719
  • Rank 16,756 (Top 0.4 %)
  • Language
    C++
  • License
    MIT License
  • Created over 5 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A dbg(…) macro for C++

dbg(…)

Build status Try it online License: MIT

A macro for printf-style debugging fans.

Debuggers are great. But sometimes you just don't have the time or patience to set up everything correctly and just want a quick way to inspect some values at runtime.

This projects provides a single header file with a dbg(…) macro that can be used in all circumstances where you would typically write printf("…", …) or std::cout << …. But it comes with a few extras.

Examples

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

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

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

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

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

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

  factorial(4);

  return 0;
}

The code above produces this output (try it yourself):

dbg(…) macro output

Features

  • Easy to read, colorized output (colors auto-disable when the output is not an interactive terminal)
  • Prints file name, line number, function name and the original expression
  • Adds type information for the printed-out value
  • Specialized pretty-printers for containers, pointers, string literals, enums, std::optional, etc.
  • Can be used inside expressions (passing through the original value)
  • The dbg.h header issues a compiler warning when included (so you don't forget to remove it).
  • Compatible and tested with C++11, C++14 and C++17.

Installation

To make this practical, the dbg.h header should be readily available from all kinds of different places and in all kinds of environments. The quick & dirty way is to actually copy the header file to /usr/local/include or to clone the repository and symlink dbg.h to /usr/local/include/dbg.h.

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

If you don't want to make untracked changes to your filesystem, check below if there is a package for your operating system or package manager.

On Arch Linux

You can install dbg-macro from the AUR:

yay -S dbg-macro

With vcpkg

You can install the dbg-macro port via:

vcpkg install dbg-macro

With cmake

CMakeLists.txt

cmake_minimum_required(VERSION 3.11) # FetchContent added in cmake 3.11
project(app) # name of executable

set(CMAKE_CXX_STANDARD 17)

# dbg-macro
include(FetchContent)

FetchContent_Declare(dbg_macro GIT_REPOSITORY https://github.com/sharkdp/dbg-macro)
FetchContent_MakeAvailable(dbg_macro)

add_executable(${PROJECT_NAME} main.cpp) # your source files goes here
target_link_libraries(${PROJECT_NAME} PRIVATE dbg_macro) # make dbg.h available

main.cpp

#include <dbg.h>

int main() {
  dbg(42, "hello world", false);
  return 0;
}

Configuration

  • Set the DBG_MACRO_DISABLE flag to disable the dbg(…) macro (i.e. to make it a no-op).
  • Set the DBG_MACRO_NO_WARNING flag to disable the "'dbg.h' header is included in your code base" warnings.
  • Set the DBG_MACRO_FORCE_COLOR flag to force colored output and skip tty checks.

Advanced features

Multiple arguments

You can pass multiple arguments to the dbg(…) macro. The output of dbg(x, y, z) is same as dbg(x); dbg(y); dbg(z);:

dbg(42, "hello world", false);

Note that you have to wrap "unprotected commas" in parentheses:

dbg("a vector:", (std::vector<int>{2, 3, 4}));

Hexadecimal, octal and binary format

If you want to format integers in hexadecimal, octal or binary representation, you can simply wrap them in dbg::hex(…), dbg::oct(…) or dbg::bin(…):

const uint32_t secret = 12648430;
dbg(dbg::hex(secret));

Printing type names

dbg(…) already prints the type for each value in parenthesis (see screenshot above). But sometimes you just want to print a type (maybe because you don't have a value for that type). In this case, you can use the dbg::type<T>() helper to pretty-print a given type T. For example:

template <typename T>
void my_function_template() {
  using MyDependentType = typename std::remove_reference<T>::type&&;
  dbg(dbg::type<MyDependentType>());
}

Print the current time

To print a timestamp, you can use the dbg::time() helper:

dbg(dbg::time());

Customization

If you want dbg(…) to work for your custom datatype, you can simply overload operator<< for std::ostream&:

std::ostream& operator<<(std::ostream& out, const user_defined_type& v) {
  out << "…";
  return out;
}

If you want to modify the type name that is printed by dbg(…), you can add a custom get_type_name overload:

// Customization point for type information
namespace dbg {
    std::string get_type_name(type_tag<bool>) {
        return "truth value";
    }
}

Development

If you want to contribute to dbg-macro, here is how you can build the tests and demos:

Make sure that the submodule(s) are up to date:

git submodule update --init

Then, use the typical cmake workflow. Usage of -DCMAKE_CXX_STANDARD=17 is optional, but recommended in order to have the largest set of features enabled:

mkdir build
cd build
cmake .. -DCMAKE_CXX_STANDARD=17
make

To run the tests, simply call:

make test

You can find the unit tests in tests/basic.cpp.

Acknowledgement

This project is inspired by Rusts dbg!(…) macro.

More Repositories

1

bat

A cat(1) clone with wings.
Rust
48,695
star
2

fd

A simple, fast and user-friendly alternative to 'find'
Rust
33,228
star
3

hyperfine

A command-line benchmarking tool
Rust
18,256
star
4

hexyl

A command-line hex viewer
Rust
8,565
star
5

pastel

A command-line tool to generate, analyze, convert and manipulate colors
Rust
4,746
star
6

insect

High precision scientific calculator with support for physical units
PureScript
3,147
star
7

cube-composer

A puzzle game inspired by functional programming
PureScript
1,967
star
8

vivid

A themeable LS_COLORS generator with a rich filetype datebase
Rust
1,479
star
9

shell-functools

Functional programming tools for the shell
Python
1,133
star
10

binocle

a graphical tool to visualize binary data
Rust
964
star
11

diskus

A minimal, fast alternative to 'du -sh'
Rust
936
star
12

numbat

A statically typed programming language for scientific computations with first class support for physical dimensions and units
Rust
734
star
13

great-puzzles

A curated list of great puzzles
484
star
14

purescript-flare

A special-purpose UI library for Purescript
PureScript
286
star
15

lscolors

A Rust library and tool to colorize paths using LS_COLORS
Rust
235
star
16

trigger

Run a user-defined command on file changes
Shell
181
star
17

bugreport

Rust library to collect system and environment information for bug reports
Rust
131
star
18

quizzity

A fast-paced geography quiz
JavaScript
125
star
19

curiosity

How far does your curiosity take you?
HTML
99
star
20

lucid

A simple mock-application for programs that work with child processes
Rust
86
star
21

parachuting-robots

An interactive version of a classic puzzle
PureScript
78
star
22

purescript-sparkle

Infer user interfaces from type signatures
PureScript
75
star
23

stack-inspector

A gdb command to inspect the size of objects on the stack
Python
62
star
24

painless

Painless parameter handling for easy exploration
C++
60
star
25

yinsh

A web-based version of the board game Yinsh
Haskell
59
star
26

purescript-isometric

Isometric rendering for PureScript
PureScript
58
star
27

pysh

Python-enhanced bash scripts
Python
58
star
28

purescript-quantities

Physical quantities and units
PureScript
53
star
29

minicpp

A REPL-style development environment for small C++ snippets
Shell
48
star
30

purescript-ctprelude

A Prelude with names from category theory
PureScript
48
star
31

qrnet

A neural network that decrypts QR codes
Python
43
star
32

riffle

A simple terminal pager (as a library)
Rust
41
star
33

config-files

A set of configuration files for vim, zsh, i3, ...
Python
37
star
34

content_inspector

Fast inspection of binary buffers to guess/determine the type of content
Rust
32
star
35

factorization-diagrams

Interactive factorization diagrams
HTML
27
star
36

argmax

Rust library to deal with "argument too long" errors
Rust
20
star
37

vacuum-robot-simulator

Simulation environment for an autonomous robot
Rust
19
star
38

sub

A command-line tool for string substitutions (RustLab 2019 workshop)
Rust
16
star
39

purescript-format

Type-safe, printf-style formatting for PureScript
PureScript
15
star
40

PaperLocator

Citation parsing to quickly access publications
JavaScript
14
star
41

purescript-decimals

Arbitrary precision numbers for PureScript
PureScript
13
star
42

flare-example

Quick start project for purescript-flare
PureScript
11
star
43

fd-benchmarks

Benchmarks for 'fd'
Shell
10
star
44

tinytag

tinytag is a "URL" shortener for your filesystem
Python
10
star
45

purescript-flaredoc

Interactive documentation with Flare
PureScript
8
star
46

phd-thesis

LaTeX sources for my PhD thesis
TeX
7
star
47

level11

7
star
48

GPE-Solver

Split-step solver for the 3D (dipolar) Gross-Pitaevskii equation
C++
7
star
49

Pack-Zack

A tag-based manager for packing lists
CSS
7
star
50

latex-report

A clean and simple LaTeX template for reports
TeX
7
star
51

dp

Personal website about some of my open source projects, board games and mountainbiking.
HTML
5
star
52

cs231n

My solutions to the CS231n assignments
Jupyter Notebook
4
star
53

imdb-ratings

Statistical analysis of my IMDB movie ratings
Jupyter Notebook
3
star
54

purescript-pairs

Datatype and functions for pairs of values
PureScript
3
star
55

zehntausend

A solver for the dice game Zehntausend
Haskell
3
star
56

gnuplot-mm

GnuPlot bindings for Mathematica
Mathematica
2
star
57

talk-moderne-programmiersprachen

JavaScript
2
star
58

rock-paper-scissors

Interactive regex puzzle
HTML
2
star
59

purescript-gametree

Algorithms for two-player zero-sum games
PureScript
2
star
60

snake-factory

A work-in-progress game with monadic parsers and snakes
PureScript
1
star
61

gomoku

Five in a row
PureScript
1
star