TExcelTAD
Home › C/C++ Packages: Conan 2, vcpkg & CPM.cmake › Mini Project: fmt, spdlog & Catch2 with Conan

Mini Project: fmt, spdlog & Catch2 with Conan

Time to put the course together. You'll build wordstat, a small command-line tool that counts words, with three real dependencies, all managed by Conan 2:

Dependency Role Kind
fmt/12.1.0 formatting the report library, used directly and through spdlog
spdlog/1.17.0 logging library
catch2/3.16.0 unit tests test requirement: never propagates to consumers

Then, in Part 2, you'll build exactly the same sources with vcpkg, without touching CMakeLists.txt.

What the project looks like

text
wordstat/
├── conanfile.py           dependencies (Conan)
├── conan.lock             pinned graph, committed
├── CMakeLists.txt         build, knows nothing about Conan
├── src/
│   ├── stats.h            the library's interface
│   ├── stats.cpp          word counting + report formatting (fmt)
│   └── main.cpp           the tool (spdlog + fmt)
└── tests/
    └── test_stats.cpp     Catch2 tests

The design follows the course's rules:

  • conanfile.py declares fmt with a bounded range, spdlog exactly, and Catch2 as a test_requires (Consuming Packages with conanfile.py).
  • CMakeLists.txt uses only find_package(... CONFIG) and namespaced targets, so any package manager can satisfy it (Conan vs vcpkg vs CPM).
  • The core logic lives in a small library, wordstat_core, which both the tool and the tests link. Tests never need main.cpp.
  • Tests are registered with catch_discover_tests, one CTest test per Catch2 test case, and always run with --rng-seed 1 so the test order is the same on every run.
  • conan.lock pins the resolved graph (Lockfiles).

Build it

This session is the whole project: it writes every file, locks, installs, builds, runs the tool and the tests. Read the files first, then the five numbered steps of output.

bash · try it yourself
mkdir -p wordstat/src wordstat/tests && cd wordstat
cat > conanfile.py <<'PY'
from conan import ConanFile
from conan.tools.cmake import cmake_layout

class WordstatConan(ConanFile):
    settings = "os", "compiler", "build_type", "arch"
    generators = "CMakeDeps", "CMakeToolchain"

    def requirements(self):
        self.requires("fmt/[>=12.1 <13]")
        self.requires("spdlog/1.17.0")
        self.test_requires("catch2/3.16.0")

    def layout(self):
        cmake_layout(self)
PY
cat > CMakeLists.txt <<'TXT'
cmake_minimum_required(VERSION 3.25)
project(wordstat VERSION 1.0.0 LANGUAGES CXX)

find_package(fmt REQUIRED CONFIG)
find_package(spdlog REQUIRED CONFIG)

add_library(wordstat_core src/stats.cpp)
target_include_directories(wordstat_core PUBLIC src)
target_link_libraries(wordstat_core PUBLIC fmt::fmt)

add_executable(wordstat src/main.cpp)
target_link_libraries(wordstat PRIVATE wordstat_core spdlog::spdlog)

include(CTest)
if(BUILD_TESTING)
  find_package(Catch2 3 REQUIRED CONFIG)
  add_executable(wordstat_tests tests/test_stats.cpp)
  target_link_libraries(wordstat_tests PRIVATE wordstat_core Catch2::Catch2WithMain)
  include(Catch)
  catch_discover_tests(wordstat_tests EXTRA_ARGS --rng-seed 1)
endif()
TXT
cat > src/stats.h <<'SRC'
#pragma once
#include <map>
#include <string>

struct Stats {
    int words = 0;
    int lines = 0;
    std::map<std::string, int> counts;
};

Stats analyse(const std::string& text);
std::string report(const Stats& s, int top);
SRC
cat > src/stats.cpp <<'SRC'
#include "stats.h"
#include <algorithm>
#include <cctype>
#include <sstream>
#include <vector>
#include <fmt/format.h>

Stats analyse(const std::string& text) {
    Stats s;
    std::istringstream in(text);
    std::string line;
    while (std::getline(in, line)) {
        ++s.lines;
        std::istringstream words(line);
        std::string w;
        while (words >> w) {
            std::string clean;
            for (char c : w)
                if (std::isalpha(static_cast<unsigned char>(c)))
                    clean += static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
            if (clean.empty()) continue;
            ++s.words;
            ++s.counts[clean];
        }
    }
    return s;
}

std::string report(const Stats& s, int top) {
    std::vector<std::pair<std::string, int>> v(s.counts.begin(), s.counts.end());
    std::stable_sort(v.begin(), v.end(), [](auto& a, auto& b) { return a.second > b.second; });
    std::string out = fmt::format("{} lines, {} words, {} distinct\n", s.lines, s.words, s.counts.size());
    for (int i = 0; i < top && i < static_cast<int>(v.size()); ++i)
        out += fmt::format("{:>2}. {:<8} {:>3}\n", i + 1, v[i].first, v[i].second);
    return out;
}
SRC
cat > src/main.cpp <<'SRC'
#include <spdlog/spdlog.h>
#include <fmt/core.h>
#include "stats.h"

int main() {
    spdlog::set_pattern("[%l] %v");
    const std::string text =
        "The build is green.\n"
        "The cache is warm, the build is fast.\n"
        "Ship the build!\n";
    spdlog::info("built with fmt {}", FMT_VERSION);
    spdlog::info("analysing {} bytes", text.size());
    Stats s = analyse(text);
    fmt::print("{}", report(s, 3));
    if (s.words > 10) spdlog::warn("long text: {} words", s.words);
}
SRC
cat > tests/test_stats.cpp <<'SRC'
#include <catch2/catch_test_macros.hpp>
#include "stats.h"

TEST_CASE("counts words and lines") {
    Stats s = analyse("one two\nthree\n");
    REQUIRE(s.lines == 2);
    REQUIRE(s.words == 3);
}

TEST_CASE("ignores case and punctuation") {
    Stats s = analyse("Build, build! BUILD.");
    REQUIRE(s.counts.size() == 1);
    CHECK(s.counts.at("build") == 3);
}

TEST_CASE("report lists the most frequent word first") {
    std::string r = report(analyse("b a b"), 1);
    CHECK(r == "1 lines, 3 words, 2 distinct\n 1. b          2\n");
}
SRC
echo "=== 1. lock the dependency graph"
conan lock create . 2>&1 | grep -E 'Resolved|: fmt|Generated lockfile' | sed "s#$HOME#~#"
echo "=== 2. install with the lockfile"
conan install . --lockfile=conan.lock -c tools.build:jobs=1 2>&1 | sed -n '/Computing necessary packages/,/^$/p'
echo "=== 3. configure and build"
cmake --preset conan-release | grep -E 'Conan: (Component )?[Tt]arget'
cmake --build --preset conan-release
echo "=== 4. run"
./build/Release/wordstat
echo "=== 5. test"
ctest --preset conan-release
./build/Release/wordstat_tests --rng-seed 1
=== 1. lock the dependency graph
Resolved version ranges
    fmt/[>=12.1 <13]: fmt/12.1.0
Generated lockfile: ~/wordstat/conan.lock
=== 2. install with the lockfile
======== Computing necessary packages ========
Requirements
    fmt/12.1.0#6baf0fb8351783472b94ee6e36232391:e02956bd268869d4519cb2b90dc7b4e51911a5d0#a857dc2fda2e0c13d61393798f6a9684 - Cache
    spdlog/1.17.0#bcbaaf7147bda6ad24ffbd1ac3d7142c:68cf2b888a31d527b3476ac5bf6707b2db1ccd2d#81ce70d6997cc1fbe7ed27c13c7c4bac - Cache
Test requirements
    catch2/3.16.0#95f400ca2fba9f0c5ce5aea6e6fe0055:0f8cc6d42d139bedbf85b2468778df7dbd2bd497#51fbd0c42ce1e195fba90c976273f23d - Cache
Build requirements
Skipped build binaries
    cmake/4.4.4

=== 3. configure and build
-- Conan: Component target declared 'fmt::fmt'
-- Conan: Component target declared 'spdlog::spdlog'
-- Conan: Component target declared 'Catch2::Catch2'
-- Conan: Component target declared 'Catch2::Catch2WithMain'
[ 16%] Building CXX object CMakeFiles/wordstat_core.dir/src/stats.cpp.o
[ 33%] Linking CXX static library libwordstat_core.a
[ 33%] Built target wordstat_core
[ 50%] Building CXX object CMakeFiles/wordstat.dir/src/main.cpp.o
[ 66%] Linking CXX executable wordstat
[ 66%] Built target wordstat
[ 83%] Building CXX object CMakeFiles/wordstat_tests.dir/tests/test_stats.cpp.o
[100%] Linking CXX executable wordstat_tests
[100%] Built target wordstat_tests
=== 4. run
[info] built with fmt 120100
[info] analysing 74 bytes
3 lines, 15 words, 8 distinct
 1. the        4
 2. build      3
 3. is         3
[warning] long text: 15 words
=== 5. test
Test project /home/learner/wordstat/build/Release
    Start 1: counts words and lines
1/3 Test #1: counts words and lines ......................   Passed    0.00 sec
    Start 2: ignores case and punctuation
2/3 Test #2: ignores case and punctuation ................   Passed    0.00 sec
    Start 3: report lists the most frequent word first
3/3 Test #3: report lists the most frequent word first ...   Passed    0.00 sec

100% tests passed out of 3

Total Test time (real) =   0.01 sec
Randomness seeded to: 1
===============================================================================
All tests passed (5 assertions in 3 test cases)

What to check in the output:

  1. Lock: the range fmt/[>=12.1 <13] resolved to fmt/12.1.0, and the lockfile now records it with its recipe revision. Commit conan.lock.
  2. Install: every binary came from the Cache, Catch2 is listed under Test requirements, and the cmake tool that Catch2 would need to build itself was skipped.
  3. Configure: CMakeDeps declared the four targets the project links: fmt::fmt, spdlog::spdlog, Catch2::Catch2 and Catch2::Catch2WithMain.
  4. Run: the tool logs through spdlog (with a fixed pattern, so there are no timestamps) and prints a report formatted by fmt. built with fmt 120100 is FMT_VERSION for 12.1.0.
  5. Test: CTest ran the three discovered test cases one by one, then the test binary ran directly, seeded, with its five assertions.

Make it yours

Extend the project, one step at a time, re-running the session after each:

  1. Add a requirement. Require nlohmann_json (or any library) in conanfile.py, and watch conan install --lockfile=conan.lock fail until you extend the lockfile with --lockfile-partial --lockfile-out=conan.lock. (Offline, only the three seeded packages exist; on your own machine with network access, any ConanCenter package works.)
  2. Add a Debug configuration. conan install . -s build_type=Debug --build=missing builds Debug binaries of all three dependencies; then use the conan-debug presets.
  3. Make it a package. Add name, version, exports_sources, build(), package() and package_info() (with self.cpp_info.libs = ["wordstat_core"]), plus a test_package, and run conan create . (Creating a Package).
  4. Wire up CI. Turn the session into ci.sh and a workflow that caches binaries on a remote (Package Managers in CI).

Checklist

  • conanfile.py with exact or bounded versions, Catch2 as test_requires
  • CMakeLists.txt with no package-manager-specific code
  • conan.lock committed, CI installs with --lockfile
  • build/ and CMakeUserPresets.json in .gitignore
  • tests run with a fixed seed and pass through ctest
  • a team profile committed (compiler, cppstd, generator) and used in CI

Test yourself

Why is Catch2 a test_requires and not a normal requirement?

  1. It's header-only
  2. Only this project's tests need it; it must not propagate to anyone who consumes wordstat
  3. Conan can't build Catch2
  4. test_requires is faster

Why does the tool link wordstat_core instead of compiling stats.cpp twice?

  1. CMake requires it
  2. Both the tool and the tests link the same library target, so the tests check exactly the code the tool uses
  3. It's faster to type
  4. Conan needs a library

What does --rng-seed 1 do for the Catch2 test run?

  1. Runs one test
  2. Fixes the random seed, so the test order and any randomised behaviour are the same on every run
  3. Enables debugging
  4. Skips slow tests