TExcelTAD
Home › Modern CMake (with CTest & CPack) › Mini Project 1: Library & App

Mini Project 1: Library & App

The Mini Project puts the whole course together in one realistic project, built in three parts:

Part Adds Course lessons it uses
1. Library & App (this lesson) a shared library with a public API, an export header, a generated version header, a program using it, install rules, an exported CMake package Targets, Install & Export, Configuration
2. Presets & Tests CMakePresets.json, unit tests, CLI tests with a fixture, labels Presets, CTest
3. Package & Consume CPack TGZ and DEB packages (runtime + dev), a workflow preset, and a separate project that uses the installed package via find_package CPack, Package Config Files

The project is TextStats: a library that counts lines, words and characters in text, and wcstats, a small wc-like program built on it. Every session runs for real, and each part's session recreates the project from scratch (sessions don't share files), so you can copy any one of them and run it on your own machine.

The layout

text
textstats/
├── CMakeLists.txt
├── cmake/
│   ├── TextStatsConfig.cmake.in     package config template
│   └── version.hpp.in               version header template
├── include/textstats/textstats.hpp  public API
├── src/textstats.cpp                implementation
└── apps/wcstats.cpp                 the program

Design decisions

  • Shared by default, static on request. BUILD_SHARED_LIBS defaults to ON only when TextStats is the top-level project; a parent project embedding it keeps its own choice.
  • Hidden symbols, explicit exports. CXX_VISIBILITY_PRESET hidden plus generate_export_header give a TEXTSTATS_EXPORT macro that works on Linux, macOS and Windows (Shared Libraries).
  • Versioned shared library. VERSION 1.2.0 / SOVERSION 1 give libtextstats.so.1.2.0 with the soname libtextstats.so.1.
  • Generated headers in the build tree, installed together with the real header through one FILE_SET HEADERS with two base directories (File Sets).
  • Relocatable install: wcstats gets the RUNPATH $ORIGIN/../lib (RPATH), and the exported package uses paths relative to itself.
  • Components from the start: every install rule is tagged runtime or dev, ready for Part 3's packages.
  • A real package: TextStatsConfig.cmake, TextStatsConfigVersion.cmake (SameMajorVersion) and the exported TextStats::textstats target (Package Config Files).

Build, run, install

The session creates every file (read the CMakeLists.txt heredoc: it is the heart of the project), builds in Release, runs the program, installs into ~/sdk, and checks the installed tree.

bash · try it yourself
# ---- create the project (Mini Project part 1) ----
mkdir -p textstats/include/textstats textstats/src textstats/apps textstats/cmake && 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)

# ---- 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()

# ---- 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)
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
# ---- build and run ----
cmake -S . -B build -G Ninja --log-level=NOTICE -DCMAKE_BUILD_TYPE=Release > /dev/null
cmake --build build
printf 'the quick brown fox\njumps over\nthe lazy dog\n' > sample.txt
./build/wcstats --version
./build/wcstats sample.txt missing.txt
echo "exit code: $?"
echo "--- exported symbols (only the API)"
nm -DC --defined-only build/libtextstats.so | grep textstats
# ---- install ----
cmake --install build --prefix "$HOME/sdk" > /dev/null
cd ~ && tree sdk
readelf -d sdk/bin/wcstats | grep -E 'NEEDED.*textstats|RUNPATH'
sdk/bin/wcstats --version
[1/5] Building CXX object CMakeFiles/textstats.dir/src/textstats.cpp.o
[2/5] Linking CXX shared library libtextstats.so.1.2.0
[3/5] Creating library symlink libtextstats.so.1 libtextstats.so
[4/5] Building CXX object CMakeFiles/wcstats.dir/apps/wcstats.cpp.o
[5/5] Linking CXX executable wcstats
wcstats (TextStats 1.2.0)
sample.txt: lines=3 words=9 chars=44
missing.txt: cannot open
exit code: 1
--- exported symbols (only the API)
0000000000001120 T textstats::count(std::basic_string_view<char, std::char_traits<char> >)
00000000000011b0 T textstats::version[abi:cxx11]()
sdk
├── bin
│   └── wcstats
├── include
│   └── textstats
│       ├── export.hpp
│       ├── textstats.hpp
│       └── version.hpp
└── lib
    ├── cmake
    │   └── TextStats
    │       ├── TextStatsConfig.cmake
    │       ├── TextStatsConfigVersion.cmake
    │       ├── TextStatsTargets-release.cmake
    │       └── TextStatsTargets.cmake
    ├── libtextstats.so -> libtextstats.so.1
    ├── libtextstats.so.1 -> libtextstats.so.1.2.0
    └── libtextstats.so.1.2.0

7 directories, 11 files
 0x0000000000000001 (NEEDED)             Shared library: [libtextstats.so.1]
 0x000000000000001d (RUNPATH)            Library runpath: [$ORIGIN/../lib]
wcstats (TextStats 1.2.0)

Check the results against the design:

  • wcstats handled a missing file and returned exit code 1, which Part 2's tests rely on.
  • nm shows only textstats::count and textstats::version: the anonymous-namespace helper is_space stayed hidden.
  • The install tree has the library with its soname links, both generated headers next to the real one, and the four CMake package files.
  • The installed wcstats needs libtextstats.so.1 and finds it through $ORIGIN/../lib, so the sdk folder can be moved anywhere.

The static variant

Because the library uses BUILD_SHARED_LIBS instead of hard-coding SHARED, a static build is a configure option away, and the same export logic produces a static package:

bash · try it yourself
# ---- create the project (Mini Project part 1) ----
mkdir -p textstats/include/textstats textstats/src textstats/apps textstats/cmake && 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)

# ---- 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()

# ---- 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)
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
cmake -S . -B build -G Ninja --log-level=NOTICE -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF > /dev/null
cmake --build build > /dev/null
cmake --install build --prefix "$HOME/sdk-static" > /dev/null
find ~/sdk-static -name '*.a' -o -name '*.so*' | sed "s#$HOME/##"
grep -o 'add_library(TextStats::textstats [A-Z]* IMPORTED)' ~/sdk-static/lib/cmake/TextStats/TextStatsTargets.cmake
readelf -d ~/sdk-static/bin/wcstats | grep -c textstats || true
sdk-static/lib/libtextstats.a
add_library(TextStats::textstats STATIC IMPORTED)
0

The package now describes a STATIC IMPORTED target, and wcstats no longer depends on any libtextstats.so (zero matching dynamic entries). For a static library the export header defines TEXTSTATS_EXPORT correctly too: generate_export_header writes a TEXTSTATS_STATIC_DEFINE check, and CMake defines it for consumers of static builds only if you add it (here it is unnecessary on Linux; on Windows add target_compile_definitions(textstats PUBLIC

lt;
lt;NOT:
lt;BOOL:${BUILD_SHARED_LIBS}>>:TEXTSTATS_STATIC_DEFINE>)
).

Checklist for Part 1

  • One library target with a namespaced ALIAS, one program target.
  • Public header under include/textstats/, included as <textstats/…>.
  • Exported symbols controlled by visibility + export macro.
  • Version from project() flows into the soname, the version header and the package version file.
  • cmake --install produces a relocatable tree with a working find_package package.

Next: Part 2: Presets & Tests.

Test yourself

Why does TextStats call add_library without SHARED or STATIC?

  1. CMake requires it
  2. So BUILD_SHARED_LIBS decides, letting users and packagers choose shared or static at configure time
  3. SHARED is deprecated
  4. To build both at once

Why are export.hpp and version.hpp listed in the HEADERS file set with a second base directory?

  1. To compile them
  2. They are generated in the build tree, but must be installed next to textstats.hpp under include/textstats/
  3. File sets require two base directories
  4. To hide them