TExcelTAD
Home › Modern CMake (with CTest & CPack) › Mini Project 3: Package & Consume

Mini Project 3: Package & Consume

The last part ships TextStats: CPack turns the install rules from Part 1 into a .tar.gz and two Debian packages, the release workflow from Part 2 gains a package step, and a separate project proves the result works by finding the installed package with find_package and building against it.

What's new

At the end of CMakeLists.txt, only when TextStats is the top-level project:

  • CPACK_GENERATOR TGZ DEB: one archive with everything, plus Debian packages.
  • CPACK_DEB_COMPONENT_INSTALL ON: one .deb per install component, so the runtime and dev tags from Part 1 become textstats (the library's shared object and wcstats) and libtextstats-dev (headers, the libtextstats.so link, the CMake package files), with libtextstats-dev depending on textstats (Components).

In CMakePresets.json: a release package preset and a fourth step in the release workflow.

Build, test and package in one command

bash · try it yourself
# ---- create the project (Mini Project part 3) ----
mkdir -p textstats/include/textstats textstats/src textstats/apps textstats/cmake textstats/tests && cd textstats
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25...4.4)
project(TextStats VERSION 1.2.0
  DESCRIPTION "Line, word and character statistics"
  LANGUAGES CXX)

include(GNUInstallDirs)
include(GenerateExportHeader)
include(CMakePackageConfigHelpers)

if(PROJECT_IS_TOP_LEVEL)
  option(BUILD_SHARED_LIBS "Build shared libraries" ON)
endif()
option(TEXTSTATS_BUILD_APP "Build the wcstats program" ON)
option(TEXTSTATS_BUILD_TESTS "Build the TextStats tests" ${PROJECT_IS_TOP_LEVEL})

# ---- the library ------------------------------------------------------------
add_library(textstats src/textstats.cpp)
add_library(TextStats::textstats ALIAS textstats)
set_target_properties(textstats PROPERTIES
  VERSION ${PROJECT_VERSION}
  SOVERSION ${PROJECT_VERSION_MAJOR}
  CXX_VISIBILITY_PRESET hidden
  VISIBILITY_INLINES_HIDDEN ON)
target_compile_features(textstats PUBLIC cxx_std_17)

set(gen ${CMAKE_CURRENT_BINARY_DIR}/generated)
generate_export_header(textstats EXPORT_FILE_NAME ${gen}/textstats/export.hpp)
configure_file(cmake/version.hpp.in ${gen}/textstats/version.hpp @ONLY)
target_sources(textstats PUBLIC
  FILE_SET HEADERS
  BASE_DIRS include ${gen}
  FILES include/textstats/textstats.hpp
        ${gen}/textstats/export.hpp
        ${gen}/textstats/version.hpp)

# ---- the program -------------------------------------------------------------
if(TEXTSTATS_BUILD_APP)
  add_executable(wcstats apps/wcstats.cpp)
  target_link_libraries(wcstats PRIVATE TextStats::textstats)
  file(RELATIVE_PATH bin_to_lib ${CMAKE_INSTALL_FULL_BINDIR} ${CMAKE_INSTALL_FULL_LIBDIR})
  set_target_properties(wcstats PROPERTIES INSTALL_RPATH "$ORIGIN/${bin_to_lib}")
endif()

# ---- tests ---------------------------------------------------------------------
if(TEXTSTATS_BUILD_TESTS)
  enable_testing()
  add_subdirectory(tests)
endif()

# ---- install + export ----------------------------------------------------------
set(cmake_dir ${CMAKE_INSTALL_LIBDIR}/cmake/TextStats)
install(TARGETS textstats EXPORT TextStatsTargets
  LIBRARY COMPONENT runtime NAMELINK_COMPONENT dev
  ARCHIVE COMPONENT dev
  RUNTIME COMPONENT runtime
  FILE_SET HEADERS COMPONENT dev)
if(TEXTSTATS_BUILD_APP)
  install(TARGETS wcstats RUNTIME COMPONENT runtime)
endif()
install(EXPORT TextStatsTargets NAMESPACE TextStats::
  DESTINATION ${cmake_dir} COMPONENT dev)
configure_package_config_file(cmake/TextStatsConfig.cmake.in
  ${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfig.cmake
  INSTALL_DESTINATION ${cmake_dir})
write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfigVersion.cmake
  COMPATIBILITY SameMajorVersion)
install(FILES
  ${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfig.cmake
  ${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfigVersion.cmake
  DESTINATION ${cmake_dir} COMPONENT dev)
export(EXPORT TextStatsTargets NAMESPACE TextStats::
  FILE ${CMAKE_CURRENT_BINARY_DIR}/TextStatsTargets.cmake)

# ---- packaging -----------------------------------------------------------------
if(PROJECT_IS_TOP_LEVEL)
  set(CPACK_PACKAGE_NAME textstats)
  set(CPACK_PACKAGE_VENDOR "TAD Tools")
  set(CPACK_PACKAGE_CONTACT "Ada Lovelace <ada@example.com>")
  set(CPACK_GENERATOR TGZ DEB)
  # DEB: one package per component, named the Debian way
  set(CPACK_DEB_COMPONENT_INSTALL ON)
  set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT)
  set(CPACK_DEBIAN_RUNTIME_PACKAGE_NAME textstats)
  set(CPACK_DEBIAN_DEV_PACKAGE_NAME libtextstats-dev)
  set(CPACK_DEBIAN_RUNTIME_PACKAGE_DEPENDS "libc6 (>= 2.34), libstdc++6 (>= 13)")
  set(CPACK_COMPONENT_DEV_DEPENDS runtime)
  set(CPACK_DEBIAN_ENABLE_COMPONENT_DEPENDS ON)
  include(CPack)
endif()
CM
cat > cmake/TextStatsConfig.cmake.in <<'CM'
@PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/TextStatsTargets.cmake")
check_required_components(TextStats)
CM
cat > cmake/version.hpp.in <<'SRC'
#pragma once
#define TEXTSTATS_VERSION "@PROJECT_VERSION@"
#define TEXTSTATS_VERSION_MAJOR @PROJECT_VERSION_MAJOR@
SRC
cat > include/textstats/textstats.hpp <<'SRC'
#pragma once
#include <cstddef>
#include <string>
#include <string_view>
#include <textstats/export.hpp>

namespace textstats {
struct Stats { std::size_t lines = 0, words = 0, chars = 0; };
TEXTSTATS_EXPORT Stats count(std::string_view text);
TEXTSTATS_EXPORT std::string version();
}  // namespace textstats
SRC
cat > src/textstats.cpp <<'SRC'
#include <textstats/textstats.hpp>
#include <textstats/version.hpp>
#include <cctype>

namespace textstats {
namespace {
bool is_space(char c) { return std::isspace(static_cast<unsigned char>(c)) != 0; }
}
Stats count(std::string_view text) {
    Stats s;
    bool in_word = false;
    for (char c : text) {
        ++s.chars;
        if (c == '\n') ++s.lines;
        if (is_space(c)) in_word = false;
        else if (!in_word) { in_word = true; ++s.words; }
    }
    if (!text.empty() && text.back() != '\n') ++s.lines;
    return s;
}
std::string version() { return TEXTSTATS_VERSION; }
}  // namespace textstats
SRC
cat > apps/wcstats.cpp <<'SRC'
#include <cstdio>
#include <cstring>
#include <fstream>
#include <sstream>
#include <textstats/textstats.hpp>

int main(int argc, char** argv) {
    if (argc < 2) { std::puts("usage: wcstats FILE... | --version"); return 2; }
    if (std::strcmp(argv[1], "--version") == 0) {
        std::printf("wcstats (TextStats %s)\n", textstats::version().c_str());
        return 0;
    }
    int status = 0;
    for (int i = 1; i < argc; ++i) {
        std::ifstream in(argv[i]);
        if (!in) { std::printf("%s: cannot open\n", argv[i]); status = 1; continue; }
        std::stringstream buf;
        buf << in.rdbuf();
        textstats::Stats s = textstats::count(buf.str());
        std::printf("%s: lines=%zu words=%zu chars=%zu\n", argv[i], s.lines, s.words, s.chars);
    }
    return status;
}
SRC
cat > tests/CMakeLists.txt <<'CM'
add_executable(textstats_tests test_textstats.cpp)
target_link_libraries(textstats_tests PRIVATE TextStats::textstats)
foreach(t count empty version)
  add_test(NAME unit.${t} COMMAND textstats_tests ${t})
endforeach()
set_tests_properties(unit.count unit.empty unit.version PROPERTIES LABELS unit)

if(TARGET wcstats)
  # A fixture copies the sample file into the test directory and removes it afterwards.
  add_test(NAME cli.setup COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/sample.txt sample.txt)
  add_test(NAME cli.cleanup COMMAND ${CMAKE_COMMAND} -E rm -f sample.txt)
  add_test(NAME cli.counts COMMAND wcstats sample.txt)
  add_test(NAME cli.missing COMMAND wcstats no-such-file.txt)
  set_tests_properties(cli.setup PROPERTIES FIXTURES_SETUP sample)
  set_tests_properties(cli.cleanup PROPERTIES FIXTURES_CLEANUP sample)
  set_tests_properties(cli.counts PROPERTIES FIXTURES_REQUIRED sample
    PASS_REGULAR_EXPRESSION "lines=3 words=9 chars=44")
  set_tests_properties(cli.missing PROPERTIES WILL_FAIL TRUE)
  set_tests_properties(cli.setup cli.cleanup cli.counts cli.missing PROPERTIES LABELS cli)
endif()
CM
cat > tests/test_textstats.cpp <<'SRC'
#include <cstdio>
#include <cstring>
#include <textstats/textstats.hpp>
#include <textstats/version.hpp>

#define CHECK(e) do { if (!(e)) { std::printf("FAILED: %s (line %d)\n", #e, __LINE__); return 1; } } while (0)

int main(int argc, char** argv) {
    const char* t = argc > 1 ? argv[1] : "";
    if (!std::strcmp(t, "count")) {
        textstats::Stats s = textstats::count("one two\nthree\n");
        CHECK(s.lines == 2); CHECK(s.words == 3); CHECK(s.chars == 14);
    } else if (!std::strcmp(t, "empty")) {
        textstats::Stats s = textstats::count("");
        CHECK(s.lines == 0 && s.words == 0 && s.chars == 0);
    } else if (!std::strcmp(t, "version")) {
        CHECK(textstats::version() == TEXTSTATS_VERSION);
    } else {
        std::printf("unknown test '%s'\n", t);
        return 2;
    }
    std::printf("%s: ok\n", t);
    return 0;
}
SRC
printf 'the quick brown fox\njumps over\nthe lazy dog\n' > tests/sample.txt
cat > CMakePresets.json <<'JSON'
{
  "version": 6,
  "cmakeMinimumRequired": { "major": 3, "minor": 25, "patch": 0 },
  "configurePresets": [
    {
      "name": "base",
      "hidden": true,
      "generator": "Ninja",
      "binaryDir": "${sourceDir}/build/${presetName}",
      "cacheVariables": { "CMAKE_EXPORT_COMPILE_COMMANDS": "ON" }
    },
    { "name": "dev", "displayName": "Development (Debug)", "inherits": "base",
      "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" } },
    { "name": "release", "displayName": "Release", "inherits": "base",
      "cacheVariables": { "CMAKE_BUILD_TYPE": "Release" } }
  ],
  "buildPresets": [
    { "name": "dev", "configurePreset": "dev" },
    { "name": "release", "configurePreset": "release" }
  ],
  "testPresets": [
    { "name": "dev", "configurePreset": "dev",
      "output": { "outputOnFailure": true },
      "execution": { "noTestsAction": "error" } },
    { "name": "release", "inherits": "dev", "configurePreset": "release" }
  ],
  "packagePresets": [
    { "name": "release", "configurePreset": "release", "generators": ["TGZ", "DEB"] }
  ],
  "workflowPresets": [
    {
      "name": "release",
      "steps": [
        { "type": "configure", "name": "release" },
        { "type": "build", "name": "release" },
        { "type": "test", "name": "release" },
        { "type": "package", "name": "release" }
      ]
    }
  ]
}
JSON
cmake --workflow --preset release 2>&1 | grep -E '^Executing|tests passed|package:'
cd build/release
echo "=== the archive"
tar -tzf textstats-1.2.0-Linux.tar.gz | grep -v '/
  


for deb in textstats_1.2.0_amd64.deb libtextstats-dev_1.2.0_amd64.deb; do
  echo "=== $deb"
  dpkg-deb --field $deb Package Version Depends
  dpkg-deb --contents $deb | awk '$1 !~ /^d/ {print "   ", $6, $7, $8}'
done
Executing workflow step 1 of 4: configure preset "release"
Executing workflow step 2 of 4: build preset "release"
Executing workflow step 3 of 4: test preset "release"
100% tests passed out of 7
Executing workflow step 4 of 4: package preset "release"
CPack: - package: /home/learner/textstats/build/release/textstats-1.2.0-Linux.tar.gz generated.
CPack: - package: /home/learner/textstats/build/release/libtextstats-dev_1.2.0_amd64.deb generated.
CPack: - package: /home/learner/textstats/build/release/textstats_1.2.0_amd64.deb generated.
=== the archive
textstats-1.2.0-Linux/bin/wcstats
textstats-1.2.0-Linux/include/textstats/export.hpp
textstats-1.2.0-Linux/include/textstats/textstats.hpp
textstats-1.2.0-Linux/include/textstats/version.hpp
textstats-1.2.0-Linux/lib/cmake/TextStats/TextStatsConfig.cmake
textstats-1.2.0-Linux/lib/cmake/TextStats/TextStatsConfigVersion.cmake
textstats-1.2.0-Linux/lib/cmake/TextStats/TextStatsTargets-release.cmake
textstats-1.2.0-Linux/lib/cmake/TextStats/TextStatsTargets.cmake
textstats-1.2.0-Linux/lib/libtextstats.so
textstats-1.2.0-Linux/lib/libtextstats.so.1
textstats-1.2.0-Linux/lib/libtextstats.so.1.2.0
=== textstats_1.2.0_amd64.deb
Package: textstats
Version: 1.2.0
Depends: libc6 (>= 2.34), libstdc++6 (>= 13)
    ./usr/bin/wcstats
    ./usr/lib/libtextstats.so.1 -> libtextstats.so.1.2.0
    ./usr/lib/libtextstats.so.1.2.0
=== libtextstats-dev_1.2.0_amd64.deb
Package: libtextstats-dev
Version: 1.2.0
Depends: textstats (= 1.2.0)
    ./usr/include/textstats/export.hpp
    ./usr/include/textstats/textstats.hpp
    ./usr/include/textstats/version.hpp
    ./usr/lib/cmake/TextStats/TextStatsConfig.cmake
    ./usr/lib/cmake/TextStats/TextStatsConfigVersion.cmake
    ./usr/lib/cmake/TextStats/TextStatsTargets-release.cmake
    ./usr/lib/cmake/TextStats/TextStatsTargets.cmake
    ./usr/lib/libtextstats.so -> libtextstats.so.1

That is a complete release from a clean checkout: configured, built, 7 tests passed, and three packages written. The split follows Debian conventions: a user who only runs wcstats installs textstats; a developer also installs libtextstats-dev, which pulls in the exact matching runtime version (textstats (= 1.2.0)).

Consume the package from another project

The real test of a package is a project that has never seen TextStats' source. This session builds the packages, unpacks both .deb files into a fake root (as apt install would put them under /usr) and the archive into ~/opt, then builds a consumer against each with nothing but find_package:

bash · try it yourself
# ---- create the project (Mini Project part 3) ----
mkdir -p textstats/include/textstats textstats/src textstats/apps textstats/cmake textstats/tests && cd textstats
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25...4.4)
project(TextStats VERSION 1.2.0
  DESCRIPTION "Line, word and character statistics"
  LANGUAGES CXX)

include(GNUInstallDirs)
include(GenerateExportHeader)
include(CMakePackageConfigHelpers)

if(PROJECT_IS_TOP_LEVEL)
  option(BUILD_SHARED_LIBS "Build shared libraries" ON)
endif()
option(TEXTSTATS_BUILD_APP "Build the wcstats program" ON)
option(TEXTSTATS_BUILD_TESTS "Build the TextStats tests" ${PROJECT_IS_TOP_LEVEL})

# ---- the library ------------------------------------------------------------
add_library(textstats src/textstats.cpp)
add_library(TextStats::textstats ALIAS textstats)
set_target_properties(textstats PROPERTIES
  VERSION ${PROJECT_VERSION}
  SOVERSION ${PROJECT_VERSION_MAJOR}
  CXX_VISIBILITY_PRESET hidden
  VISIBILITY_INLINES_HIDDEN ON)
target_compile_features(textstats PUBLIC cxx_std_17)

set(gen ${CMAKE_CURRENT_BINARY_DIR}/generated)
generate_export_header(textstats EXPORT_FILE_NAME ${gen}/textstats/export.hpp)
configure_file(cmake/version.hpp.in ${gen}/textstats/version.hpp @ONLY)
target_sources(textstats PUBLIC
  FILE_SET HEADERS
  BASE_DIRS include ${gen}
  FILES include/textstats/textstats.hpp
        ${gen}/textstats/export.hpp
        ${gen}/textstats/version.hpp)

# ---- the program -------------------------------------------------------------
if(TEXTSTATS_BUILD_APP)
  add_executable(wcstats apps/wcstats.cpp)
  target_link_libraries(wcstats PRIVATE TextStats::textstats)
  file(RELATIVE_PATH bin_to_lib ${CMAKE_INSTALL_FULL_BINDIR} ${CMAKE_INSTALL_FULL_LIBDIR})
  set_target_properties(wcstats PROPERTIES INSTALL_RPATH "$ORIGIN/${bin_to_lib}")
endif()

# ---- tests ---------------------------------------------------------------------
if(TEXTSTATS_BUILD_TESTS)
  enable_testing()
  add_subdirectory(tests)
endif()

# ---- install + export ----------------------------------------------------------
set(cmake_dir ${CMAKE_INSTALL_LIBDIR}/cmake/TextStats)
install(TARGETS textstats EXPORT TextStatsTargets
  LIBRARY COMPONENT runtime NAMELINK_COMPONENT dev
  ARCHIVE COMPONENT dev
  RUNTIME COMPONENT runtime
  FILE_SET HEADERS COMPONENT dev)
if(TEXTSTATS_BUILD_APP)
  install(TARGETS wcstats RUNTIME COMPONENT runtime)
endif()
install(EXPORT TextStatsTargets NAMESPACE TextStats::
  DESTINATION ${cmake_dir} COMPONENT dev)
configure_package_config_file(cmake/TextStatsConfig.cmake.in
  ${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfig.cmake
  INSTALL_DESTINATION ${cmake_dir})
write_basic_package_version_file(${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfigVersion.cmake
  COMPATIBILITY SameMajorVersion)
install(FILES
  ${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfig.cmake
  ${CMAKE_CURRENT_BINARY_DIR}/TextStatsConfigVersion.cmake
  DESTINATION ${cmake_dir} COMPONENT dev)
export(EXPORT TextStatsTargets NAMESPACE TextStats::
  FILE ${CMAKE_CURRENT_BINARY_DIR}/TextStatsTargets.cmake)

# ---- packaging -----------------------------------------------------------------
if(PROJECT_IS_TOP_LEVEL)
  set(CPACK_PACKAGE_NAME textstats)
  set(CPACK_PACKAGE_VENDOR "TAD Tools")
  set(CPACK_PACKAGE_CONTACT "Ada Lovelace <ada@example.com>")
  set(CPACK_GENERATOR TGZ DEB)
  # DEB: one package per component, named the Debian way
  set(CPACK_DEB_COMPONENT_INSTALL ON)
  set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT)
  set(CPACK_DEBIAN_RUNTIME_PACKAGE_NAME textstats)
  set(CPACK_DEBIAN_DEV_PACKAGE_NAME libtextstats-dev)
  set(CPACK_DEBIAN_RUNTIME_PACKAGE_DEPENDS "libc6 (>= 2.34), libstdc++6 (>= 13)")
  set(CPACK_COMPONENT_DEV_DEPENDS runtime)
  set(CPACK_DEBIAN_ENABLE_COMPONENT_DEPENDS ON)
  include(CPack)
endif()
CM
cat > cmake/TextStatsConfig.cmake.in <<'CM'
@PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/TextStatsTargets.cmake")
check_required_components(TextStats)
CM
cat > cmake/version.hpp.in <<'SRC'
#pragma once
#define TEXTSTATS_VERSION "@PROJECT_VERSION@"
#define TEXTSTATS_VERSION_MAJOR @PROJECT_VERSION_MAJOR@
SRC
cat > include/textstats/textstats.hpp <<'SRC'
#pragma once
#include <cstddef>
#include <string>
#include <string_view>
#include <textstats/export.hpp>

namespace textstats {
struct Stats { std::size_t lines = 0, words = 0, chars = 0; };
TEXTSTATS_EXPORT Stats count(std::string_view text);
TEXTSTATS_EXPORT std::string version();
}  // namespace textstats
SRC
cat > src/textstats.cpp <<'SRC'
#include <textstats/textstats.hpp>
#include <textstats/version.hpp>
#include <cctype>

namespace textstats {
namespace {
bool is_space(char c) { return std::isspace(static_cast<unsigned char>(c)) != 0; }
}
Stats count(std::string_view text) {
    Stats s;
    bool in_word = false;
    for (char c : text) {
        ++s.chars;
        if (c == '\n') ++s.lines;
        if (is_space(c)) in_word = false;
        else if (!in_word) { in_word = true; ++s.words; }
    }
    if (!text.empty() && text.back() != '\n') ++s.lines;
    return s;
}
std::string version() { return TEXTSTATS_VERSION; }
}  // namespace textstats
SRC
cat > apps/wcstats.cpp <<'SRC'
#include <cstdio>
#include <cstring>
#include <fstream>
#include <sstream>
#include <textstats/textstats.hpp>

int main(int argc, char** argv) {
    if (argc < 2) { std::puts("usage: wcstats FILE... | --version"); return 2; }
    if (std::strcmp(argv[1], "--version") == 0) {
        std::printf("wcstats (TextStats %s)\n", textstats::version().c_str());
        return 0;
    }
    int status = 0;
    for (int i = 1; i < argc; ++i) {
        std::ifstream in(argv[i]);
        if (!in) { std::printf("%s: cannot open\n", argv[i]); status = 1; continue; }
        std::stringstream buf;
        buf << in.rdbuf();
        textstats::Stats s = textstats::count(buf.str());
        std::printf("%s: lines=%zu words=%zu chars=%zu\n", argv[i], s.lines, s.words, s.chars);
    }
    return status;
}
SRC
cat > tests/CMakeLists.txt <<'CM'
add_executable(textstats_tests test_textstats.cpp)
target_link_libraries(textstats_tests PRIVATE TextStats::textstats)
foreach(t count empty version)
  add_test(NAME unit.${t} COMMAND textstats_tests ${t})
endforeach()
set_tests_properties(unit.count unit.empty unit.version PROPERTIES LABELS unit)

if(TARGET wcstats)
  # A fixture copies the sample file into the test directory and removes it afterwards.
  add_test(NAME cli.setup COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/sample.txt sample.txt)
  add_test(NAME cli.cleanup COMMAND ${CMAKE_COMMAND} -E rm -f sample.txt)
  add_test(NAME cli.counts COMMAND wcstats sample.txt)
  add_test(NAME cli.missing COMMAND wcstats no-such-file.txt)
  set_tests_properties(cli.setup PROPERTIES FIXTURES_SETUP sample)
  set_tests_properties(cli.cleanup PROPERTIES FIXTURES_CLEANUP sample)
  set_tests_properties(cli.counts PROPERTIES FIXTURES_REQUIRED sample
    PASS_REGULAR_EXPRESSION "lines=3 words=9 chars=44")
  set_tests_properties(cli.missing PROPERTIES WILL_FAIL TRUE)
  set_tests_properties(cli.setup cli.cleanup cli.counts cli.missing PROPERTIES LABELS cli)
endif()
CM
cat > tests/test_textstats.cpp <<'SRC'
#include <cstdio>
#include <cstring>
#include <textstats/textstats.hpp>
#include <textstats/version.hpp>

#define CHECK(e) do { if (!(e)) { std::printf("FAILED: %s (line %d)\n", #e, __LINE__); return 1; } } while (0)

int main(int argc, char** argv) {
    const char* t = argc > 1 ? argv[1] : "";
    if (!std::strcmp(t, "count")) {
        textstats::Stats s = textstats::count("one two\nthree\n");
        CHECK(s.lines == 2); CHECK(s.words == 3); CHECK(s.chars == 14);
    } else if (!std::strcmp(t, "empty")) {
        textstats::Stats s = textstats::count("");
        CHECK(s.lines == 0 && s.words == 0 && s.chars == 0);
    } else if (!std::strcmp(t, "version")) {
        CHECK(textstats::version() == TEXTSTATS_VERSION);
    } else {
        std::printf("unknown test '%s'\n", t);
        return 2;
    }
    std::printf("%s: ok\n", t);
    return 0;
}
SRC
printf 'the quick brown fox\njumps over\nthe lazy dog\n' > tests/sample.txt
cat > CMakePresets.json <<'JSON'
{
  "version": 6,
  "cmakeMinimumRequired": { "major": 3, "minor": 25, "patch": 0 },
  "configurePresets": [
    {
      "name": "base",
      "hidden": true,
      "generator": "Ninja",
      "binaryDir": "${sourceDir}/build/${presetName}",
      "cacheVariables": { "CMAKE_EXPORT_COMPILE_COMMANDS": "ON" }
    },
    { "name": "dev", "displayName": "Development (Debug)", "inherits": "base",
      "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug" } },
    { "name": "release", "displayName": "Release", "inherits": "base",
      "cacheVariables": { "CMAKE_BUILD_TYPE": "Release" } }
  ],
  "buildPresets": [
    { "name": "dev", "configurePreset": "dev" },
    { "name": "release", "configurePreset": "release" }
  ],
  "testPresets": [
    { "name": "dev", "configurePreset": "dev",
      "output": { "outputOnFailure": true },
      "execution": { "noTestsAction": "error" } },
    { "name": "release", "inherits": "dev", "configurePreset": "release" }
  ],
  "packagePresets": [
    { "name": "release", "configurePreset": "release", "generators": ["TGZ", "DEB"] }
  ],
  "workflowPresets": [
    {
      "name": "release",
      "steps": [
        { "type": "configure", "name": "release" },
        { "type": "build", "name": "release" },
        { "type": "test", "name": "release" },
        { "type": "package", "name": "release" }
      ]
    }
  ]
}
JSON
cmake --workflow --preset release > /dev/null 2>&1
cd build/release
dpkg-deb -x textstats_1.2.0_amd64.deb ~/debroot
dpkg-deb -x libtextstats-dev_1.2.0_amd64.deb ~/debroot
mkdir -p ~/opt && tar -xzf textstats-1.2.0-Linux.tar.gz -C ~/opt

# ---- a separate project ----
mkdir -p ~/report && cd ~/report
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Report LANGUAGES CXX)
find_package(TextStats 1.0 REQUIRED)
message("using TextStats ${TextStats_VERSION} from ${TextStats_DIR}")
add_executable(report main.cpp)
target_link_libraries(report PRIVATE TextStats::textstats)
CM
cat > main.cpp <<'SRC'
#include <cstdio>
#include <textstats/textstats.hpp>
#include <textstats/version.hpp>
int main() {
    const char* poem = "Twinkle, twinkle, little star,\nHow I wonder what you are!\n";
    textstats::Stats s = textstats::count(poem);
    std::printf("report built against TextStats %s (major %d)\n", TEXTSTATS_VERSION, TEXTSTATS_VERSION_MAJOR);
    std::printf("poem: %zu lines, %zu words, %zu characters\n", s.lines, s.words, s.chars);
}
SRC
echo "=== against the .deb packages"
cmake -S . -B build-deb -G Ninja --log-level=NOTICE -DCMAKE_PREFIX_PATH=$HOME/debroot/usr 2>&1 | grep '^using'
cmake --build build-deb > /dev/null && ./build-deb/report
echo "=== against the .tar.gz"
cmake -S . -B build-tgz -G Ninja --log-level=NOTICE -DCMAKE_PREFIX_PATH=$HOME/opt/textstats-1.2.0-Linux 2>&1 | grep '^using'
cmake --build build-tgz > /dev/null && ./build-tgz/report
echo "=== the packaged program runs from where it was unpacked"
~/debroot/usr/bin/wcstats --version
echo "=== asking for TextStats 2 fails cleanly"
sed -i 's/TextStats 1.0 REQUIRED/TextStats 2.0 REQUIRED/' CMakeLists.txt
cmake -S . -B build-v2 -G Ninja --log-level=NOTICE -DCMAKE_PREFIX_PATH=$HOME/opt/textstats-1.2.0-Linux 2>&1 | grep -A1 'Could not find'
=== against the .deb packages
using TextStats 1.2.0 from /home/learner/debroot/usr/lib/cmake/TextStats
report built against TextStats 1.2.0 (major 1)
poem: 2 lines, 10 words, 58 characters
=== against the .tar.gz
using TextStats 1.2.0 from /home/learner/opt/textstats-1.2.0-Linux/lib/cmake/TextStats
report built against TextStats 1.2.0 (major 1)
poem: 2 lines, 10 words, 58 characters
=== the packaged program runs from where it was unpacked
wcstats (TextStats 1.2.0)
=== asking for TextStats 2 fails cleanly
  Could not find a configuration file for package "TextStats" that is
  compatible with requested version "2.0".

The consumer's CMakeLists.txt names no include directory, no library path, no C++ standard: TextStats::textstats carried all of it, from both package formats, because the exported files are relocatable. The version check from TextStatsConfigVersion.cmake rejected a request for 2.0.

Final checklist

  • cmake --workflow --preset release configures, builds, tests and packages from a clean checkout.
  • The packages contain exactly the installed files, split into runtime and dev.
  • A separate project finds the package with find_package(TextStats 1.0), from a .deb root or an unpacked archive, and builds without any extra flags.
  • The installed program runs from wherever it was unpacked.
  • Incompatible version requests fail at configure time with a clear message.

Where to go next

Test yourself

Why does the consumer need only -DCMAKE_PREFIX_PATH and no include or library paths?

  1. CMake guesses them
  2. The installed TextStatsConfig.cmake defines the imported target TextStats::textstats with its include directory, library file and compile features
  3. The paths are hard-coded in the consumer
  4. pkg-config provides them

Why does libtextstats-dev depend on textstats (= 1.2.0)?

  1. Debian requires it for every package
  2. The dev package's headers and libtextstats.so link only work with the matching runtime library, declared with CPACK_COMPONENT_DEV_DEPENDS
  3. CPack adds it to every component
  4. Because of SOVERSION