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.debper install component, so theruntimeanddevtags from Part 1 becometextstats(the library's shared object andwcstats) andlibtextstats-dev(headers, thelibtextstats.solink, the CMake package files), withlibtextstats-devdepending ontextstats(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 '/