Skip to main content
  1. Posts/

Pretty Output Format in C++

··233 words·2 mins·
Programming C++
Table of Contents

Although std::cout in C++ is powerful, it lacks the ease of use of format string in Python. Fortunately, the 3rd party package fmt provides a similar feature for C++.

Build fmt

To use the fmt package, we need to build it:

git clone --depth 1
cd fmt
mkdir build && cd build
cmake -G "Unix Makefiles" -DCMAKE_INSTALL_PREFIX=~/tools/fmt -DCMAKE_BUILD_TYPE=Release ..
make -j 8
make install

This will build the static version of fmt and install it under $HOME/tools/fmt.

To build a dynamic library, use the following cmake command instead:


How to use

Here is a short snippet to test it:

#include <iostream>
#include <vector>
#include <fmt/ranges.h>
#include <fmt/core.h>

using std::vector;

int main() {
  vector<int> arr = {1, 2, 3};

  fmt::print("arr is {}", arr);

  fmt::print("The price of {} is {} Yuan/kg", "apple", 4.2);
  return 0;

Use the following comamnd to build against the static version of fmt:

g++ -L$HOME/tools/fmt/lib64/ -I$HOME/tools/fmt/include/ -l:libfmt.a -o test_static

And the following command to build against the dynamic version of fmt:

g++ -L$HOME/tools/fmt/lib64/ -I$HOME/tools/fmt/include/ -lfmt -o test_shared

To run the dynamic executable, you need to set up the env variable LD_LIBRARY_PATH properly:

LD_LIBRARY_PATH=$HOME/tools/fmt/lib64:$LD_LIBRARY_PATH ./test_shared

The size differs significantly between the static and dynamic executable files:

32K     test_shared
220K    test_static



Static and Dynamic Linkage in C++
·387 words·2 mins
Programming C++
What Is the Correct Way of Loop Through C++ Vector Using Index?
··498 words·3 mins
Programming C++
Remainder Operator(%) in C++
··294 words·2 mins
Programming C++