If you find any mistakes here or anywhere else on my website, email website@CoryHufford.com.
November 22, 2026
This is an example CMake script for a C++ library and an accompanying set of headers and source files to make a compilable example library. A library using this CMake script should be built, tested, packaged, and installed with the normal CMake commands, for example:
mkdir build/
cd build/
cmake -G "Ninja Multi-Config" -D CMAKE_INSTALL_PREFIX=/opt/foo/ ../
cmake --build ./ -j 8 --config Release
ctest -j 8 -C Release
cpack -G "TGZ" -C Release
cmake --install ./ --config Release
This example has the following file structure:
|- include/
| |- foo/
| |- primes.hpp
| |- version.hpp
|
|- private/
| |- foo/
| |- private/
| |- numbers.hpp
|
|- source/
| |- numbers.cpp
| |- primes.cpp
| |- version.cpp.in
|
|- tests/
| |- test_numbers.cpp
| |- test_primes.cpp
| |- test_version.cpp
|
|- CMakeLists.txt
The targets created by the CMake script are:
| Target | Type | Intended for public consumption | Notes |
|---|---|---|---|
foo::foo |
Library alias | Yes | Alias for foo. |
foo_tests |
Executable | Yes | Unit test executable. Only exists if the
FOO_BUILD_TESTS option is enabled. |
foo |
Library | No | Main library target. |
foo_testable |
Interface library | No | Inherits everything from foo and is linked by
foo_tests. foo_tests links to this instead
of foo so that non-exported functions in private
headers can be unit tested. |
The unit tests use the Catch2 library
(repository). Catch2 is
retrieved using FetchContent with a FIND_PACKAGE_ARGS argument, so
it will be found by find_package() or downloaded.
FETCHCONTENT_SOURCE_DIR_CATCH2 or Catch2_ROOT can be
used to provide a local copy of the source code or prebuilt library (or, more
globally, CMAKE_PREFIX_PATH).
CMakeLists.txtcmake_minimum_required(VERSION 3.28)
include(CMakeDependentOption)
project(foo
VERSION 1.0.0
LANGUAGES CXX
DESCRIPTION "Example C++ library and CMake script"
)
option(
FOO_BUILD_TESTS
"Add test executable target(s) (built by default)"
${PROJECT_IS_TOP_LEVEL}
)
cmake_dependent_option(
FOO_WARNINGS_AS_ERRORS
"Enable warnings as errors (-Werror with GNU/Clang, /WX with MSVC)"
ON
PROJECT_IS_TOP_LEVEL
OFF
)
if(POLICY CMP0168)
# Removes FetchContent sub-builds
cmake_policy(SET CMP0168 NEW)
endif()
if(PROJECT_IS_TOP_LEVEL)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CPACK_VERBATIM_VARIABLES ON)
include(CPack)
if(CMAKE_CXX_COMPILER_FRONTEND_VARIANT MATCHES "GNU|Clang")
set(foo_compile_options
-Wall
-Wextra
-Wpedantic
-Wconversion
-Wsign-conversion
)
if(FOO_WARNINGS_AS_ERRORS)
list(APPEND foo_compile_options -Werror)
endif()
elseif(CMAKE_CXX_COMPILER_FRONTEND_VARIANT STREQUAL "MSVC")
message(NOTICE
"FOO: DLL compatibility warnings are being disabled; don't mix "
"shared libraries compiled against different MSVC runtimes."
)
set(foo_compile_options /W4 /wd4251 /wd4275)
if(FOO_WARNINGS_AS_ERRORS)
list(APPEND foo_compile_options /WX)
endif()
else()
message(WARNING
"FOO: Foo is untested with this compiler and no warnings are being "
"enabled."
)
endif()
endif()
include(CMakePackageConfigHelpers)
include(FetchContent)
include(GenerateExportHeader)
include(GNUInstallDirs)
configure_file(source/version.cpp.in version.cpp @ONLY)
find_package(Threads REQUIRED)
add_library(foo
${CMAKE_CURRENT_BINARY_DIR}/version.cpp
source/numbers.cpp
source/primes.cpp
)
target_compile_features(foo PUBLIC cxx_std_20)
target_compile_options(foo PRIVATE ${foo_compile_options})
target_link_libraries(foo PRIVATE Threads::Threads)
set_target_properties(foo
PROPERTIES
CXX_VISIBILITY_PRESET hidden
SOVERSION ${foo_VERSION_MAJOR}
VERSION ${foo_VERSION}
VISIBILITY_INLINES_HIDDEN TRUE
)
file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/fooConfig.cmake.in
"@PACKAGE_INIT@
include(CMakeFindDependencyMacro)
find_dependency(Threads)
include(\${CMAKE_CURRENT_LIST_DIR}/fooTargets.cmake)
check_required_components(foo)
")
generate_export_header(foo EXPORT_FILE_NAME include/foo/export.hpp)
write_basic_package_version_file(
${CMAKE_CURRENT_BINARY_DIR}/fooConfigVersion.cmake
COMPATIBILITY SameMajorVersion
)
configure_package_config_file(
${CMAKE_CURRENT_BINARY_DIR}/fooConfig.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/fooConfig.cmake
INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/foo/
)
target_include_directories(foo PRIVATE private/)
target_sources(foo
PUBLIC
FILE_SET HEADERS
BASE_DIRS
${CMAKE_CURRENT_BINARY_DIR}/include/
include/
FILES
${CMAKE_CURRENT_BINARY_DIR}/include/foo/export.hpp
include/foo/primes.hpp
include/foo/version.hpp
)
install(
TARGETS foo
EXPORT foo
ARCHIVE
LIBRARY
RUNTIME
FILE_SET HEADERS
)
install(
EXPORT foo
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/foo/
NAMESPACE foo::
FILE fooTargets.cmake
)
install(
FILES
${CMAKE_CURRENT_BINARY_DIR}/fooConfig.cmake
${CMAKE_CURRENT_BINARY_DIR}/fooConfigVersion.cmake
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/foo/
)
add_library(foo::foo ALIAS foo)
if(FOO_BUILD_TESTS)
enable_testing()
FetchContent_Declare(
Catch2
GIT_REPOSITORY https://github.com/catchorg/Catch2.git
GIT_TAG v3.16.1
EXCLUDE_FROM_ALL
SYSTEM
FIND_PACKAGE_ARGS 3.11.0
)
FetchContent_MakeAvailable(Catch2)
if(DEFINED catch2_SOURCE_DIR)
include(${catch2_SOURCE_DIR}/extras/Catch.cmake)
else()
include(Catch)
endif()
add_library(foo_testable INTERFACE)
target_sources(foo_testable INTERFACE $<TARGET_OBJECTS:foo>)
target_link_libraries(foo_testable
INTERFACE
$<TARGET_PROPERTY:foo,LINK_LIBRARIES>
)
target_include_directories(foo_testable
INTERFACE
$<TARGET_PROPERTY:foo,INTERFACE_INCLUDE_DIRECTORIES>
private/
)
target_compile_definitions(foo_testable INTERFACE foo_EXPORTS)
add_executable(foo_tests
tests/test_numbers.cpp
tests/test_primes.cpp
tests/test_version.cpp
)
target_compile_features(foo_tests PUBLIC cxx_std_20)
target_compile_options(foo_tests PRIVATE ${foo_compile_options})
target_link_libraries(foo_tests
PRIVATE
foo_testable
Catch2::Catch2WithMain
)
catch_discover_tests(foo_tests
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
DISCOVERY_MODE PRE_TEST
DL_PATHS $<TARGET_RUNTIME_DLL_DIRS:foo_tests>
)
endif()
include/foo/primes.hpp#pragma once
#include "foo/export.hpp"
#include <cstdint>
namespace foo {
[[nodiscard]] FOO_EXPORT std::uint32_t nth_prime(std::uint16_t n) noexcept;
}
include/foo/version.hpp#pragma once
#include "foo/export.hpp"
#include <cstddef>
#include <string>
namespace foo {
/**
* \returns Version string for this library. This library follows Semantic
* Versioning (SemVer) 2.
*/
[[nodiscard]] FOO_EXPORT std::string version() noexcept;
/**
* \returns Major version for this library. This library follows Semantic
* Versioning (SemVer) 2.
*/
[[nodiscard]] FOO_EXPORT std::size_t version_major() noexcept;
/**
* \returns Minor version for this library. This library follows Semantic
* Versioning (SemVer) 2.
*/
[[nodiscard]] FOO_EXPORT std::size_t version_minor() noexcept;
/**
* \returns Patch version for this library. This library follows Semantic
* Versioning (SemVer) 2.
*/
[[nodiscard]] FOO_EXPORT std::size_t version_patch() noexcept;
}
private/foo/private/numbers.hpp#pragma once
#include <cstdint>
namespace foo {
[[nodiscard]] bool is_prime(std::uint32_t u) noexcept;
}
source/numbers.cpp#include "foo/private/numbers.hpp"
#include <cstdint>
bool foo::is_prime(const std::uint32_t u) noexcept {
if (u < 2)
return false;
for (std::uint32_t i = 2; i < u; ++i) {
if (u % i == 0)
return false;
}
return true;
}
source/primes.cpp#include "foo/primes.hpp"
#include "foo/private/numbers.hpp"
#include <cstdint>
std::uint32_t foo::nth_prime(std::uint16_t n) noexcept {
std::uint32_t prime = 2;
for (; n > 0; --n)
for (++prime; !foo::is_prime(prime); ++prime);
return prime;
}
source/version.cpp.in#include "foo/version.hpp"
#include <cstddef>
#include <string>
std::string foo::version() noexcept {
return "@foo_VERSION@";
}
std::size_t foo::version_major() noexcept {
return @foo_VERSION_MAJOR@;
}
std::size_t foo::version_minor() noexcept {
return @foo_VERSION_MINOR@;
}
std::size_t foo::version_patch() noexcept {
return @foo_VERSION_PATCH@;
}
tests/test_numbers.cpp#include "foo/private/numbers.hpp"
#include <catch2/catch_test_macros.hpp>
TEST_CASE("is prime", "[foo][foo::is_prime]") {
CHECK(!foo::is_prime(0));
CHECK(!foo::is_prime(1));
CHECK( foo::is_prime(2));
CHECK( foo::is_prime(3));
CHECK(!foo::is_prime(4));
CHECK( foo::is_prime(5));
CHECK(!foo::is_prime(6));
CHECK( foo::is_prime(7));
CHECK(!foo::is_prime(8));
CHECK(!foo::is_prime(9));
}
tests/test_primes.cpp#include "foo/primes.hpp"
#include <catch2/catch_test_macros.hpp>
TEST_CASE("nth prime", "[foo][foo::nth_prime]") {
CHECK(foo::nth_prime(0) == 2);
CHECK(foo::nth_prime(1) == 3);
CHECK(foo::nth_prime(2) == 5);
CHECK(foo::nth_prime(3) == 7);
CHECK(foo::nth_prime(4) == 11);
CHECK(foo::nth_prime(5) == 13);
CHECK(foo::nth_prime(6) == 17);
CHECK(foo::nth_prime(7) == 19);
CHECK(foo::nth_prime(8) == 23);
CHECK(foo::nth_prime(9) == 29);
}
tests/test_version.cpp#include "foo/version.hpp"
#include <catch2/catch_test_macros.hpp>
#include <cstddef>
#include <limits>
#include <regex>
#include <string>
TEST_CASE("version string", "[foo][foo::version]") {
CHECK(std::regex_match(
foo::version(),
std::regex("^[0-9]+\\.[0-9]+\\.[0-9]+$")
));
}
TEST_CASE("version major", "[foo][foo::version_major]") {
CHECK(foo::version_major() < std::numeric_limits<unsigned>::max());
}
TEST_CASE("version minor", "[foo][foo::version_minor]") {
CHECK(foo::version_minor() < std::numeric_limits<unsigned>::max());
}
TEST_CASE("version patch", "[foo][foo::version_patch]") {
CHECK(foo::version_patch() < std::numeric_limits<unsigned>::max());
}
TEST_CASE(
"version",
"[foo][foo::version][foo::version_major][foo::version_minor]"
"[foo::version_patch]"
) {
const std::string string = foo::version();
const std::size_t major = foo::version_major();
const std::size_t minor = foo::version_minor();
const std::size_t patch = foo::version_patch();
CHECK((major != 0 || minor != 0 || patch != 0));
const std::string expected_string =
std::to_string(major)
+ '.'
+ std::to_string(minor)
+ '.'
+ std::to_string(patch);
CHECK(string == expected_string);
}