Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ or pin to a specific commit: `CPMAddPackage("gh:stlab/cpp-library#<commit-sha>")
- **`cpp-library.cmake`** (root) — entry point; defines `cpp_library_set_version()` and `cpp_library_enable_dependency_tracking()`, then includes the modules below. `cpp_library_enable_dependency_tracking()` must be called *before* `project()` — it registers `cpp-library-dependency-provider.cmake` via `CMAKE_PROJECT_TOP_LEVEL_INCLUDES` so CMake's dependency-provider hook (3.24+) is active for the `project()` call that follows.
- **`cpp-library-setup.cmake`** — the core `cpp_library_setup(...)` function (called from `cpp-library.cmake`, which is why the module split doesn't map 1:1 to files: some logic that requires `project()` to already have run — install, docs, CI templating — is deferred and included lazily inside `cpp_library_setup()` rather than at top-level `include()` time).
- **`cpp-library-install.cmake`** — install rules, package `Config.cmake`/`ConfigVersion.cmake` generation, and the `find_dependency()` derivation logic. Only `include()`d inside `cpp_library_setup()` (needs `project()` for `GNUInstallDirs`).
- **`cpp-library-dependency-provider.cmake`** — implements the CMake dependency-provider callback (`SET_DEPENDENCY_PROVIDER`) that intercepts every `find_package()`/`FetchContent_MakeAvailable()` call to record the exact package/version/components used, so `Config.cmake` can regenerate accurate `find_dependency()` calls at install time. State is stored in `GLOBAL` properties (`_CPP_LIBRARY_TRACKED_DEP_*`, `_CPP_LIBRARY_PKG_KEYS`, etc.) — there's no other persistence mechanism, so tests reset these properties between cases (see `tests/install/CMakeLists.txt`).
- **`cpp-library-dependency-provider.cmake`** — implements the CMake dependency-provider callback (`SET_DEPENDENCY_PROVIDER`) that intercepts every `find_package()`/`FetchContent_MakeAvailable()` call to record the exact package/version/components used, so `Config.cmake` can regenerate accurate `find_dependency()` calls at install time. State is stored in `GLOBAL` properties (`_CPP_LIBRARY_TRACKED_DEP_*`, `_CPP_LIBRARY_PKG_KEYS`, etc.) — there's no other persistence mechanism, so tests reset these properties between cases (see `tests/install/CMakeLists.txt`). CPM packages served from `CPM_SOURCE_CACHE` bypass `FetchContent_MakeAvailable()`, so the provider never sees them; the install module resolves CPM packages and their versions from CPM's own registry (`CPM_PACKAGES`, `CPM_PACKAGE_<name>_VERSION`) instead.
- **`cpp-library-docs.cmake`** — Doxygen + doxygen-awesome-css target (`docs`).
- **`cpp-library-ci.cmake`** — generates `.github/workflows/ci.yml` for the *consumer* project from `templates/.github/workflows/ci.yml.in`, substituting the package name.
- **`cpp-library-testing.cmake`** — public `cpp_library_copy_runtime_dlls()` helper and backward-compatibility `_cpp_library_setup_testing()` wrapper; test/example executable creation lives in `_cpp_library_setup_executables()` in `cpp-library.cmake`.
Expand All @@ -62,7 +62,7 @@ or pin to a specific commit: `CPMAddPackage("gh:stlab/cpp-library#<commit-sha>")
- Creates the library target (`INTERFACE` if no `SOURCES`, else a compiled target respecting `BUILD_SHARED_LIBS`) with `FILE_SET headers`, aliased as `NAMESPACE::CLEAN_NAME`.
- Calls `_cpp_library_setup_install()`, which is gated by `${NAMESPACE}_INSTALL` (default `PROJECT_IS_TOP_LEVEL`) and uses `cmake_language(DEFER)` to generate `Config.cmake` and register install-time dependency validation *after* all `target_link_libraries()` calls in the consumer's `CMakeLists.txt` have executed (deferred calls run LIFO — validation is registered first so it executes last, right before config files are written).
- If `PROJECT_IS_TOP_LEVEL`: also copies static template files (`.clang-format`, `.gitignore`, `CMakePresets.json`, etc. — skipped if already present unless `CPP_LIBRARY_FORCE_INIT` is set), configures the CI workflow, downloads doctest, and wires up `TESTS`/`EXAMPLES`/`docs`. When consumed as a subproject (not top-level), it returns early after target creation — "lightweight consumer mode".
4. At install time, if any dependency was linked but never went through a tracked `find_package()`/`CPMAddPackage()` call at the top-level scope (e.g. added in a subdirectory), the install step fails with a detailed error (`_cpp_library_setup_install_validation`) rather than silently emitting a broken `Config.cmake`. During plain `configure`/`build` (no install), the same situation is only a warning ("Untracked dependencies").
4. At install time, if any dependency was linked but is neither in CPM's registry nor recorded by the provider (e.g. brought in by `add_subdirectory()`, or by `find_package()` before `project()`), the install step fails with a detailed error (`_cpp_library_setup_install_validation`) rather than silently emitting a broken `Config.cmake`. During plain `configure`/`build` (no install), the same situation is only a warning ("Untracked dependencies").

### Naming conventions consumers must follow

Expand Down
65 changes: 20 additions & 45 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -679,60 +679,35 @@ During configuration, you may see messages like:

```
-- cpp-library: Untracked dependencies (see: https://github.com/stlab/cpp-library#untracked-dependencies)
-- cpp-library: Dependency stlab::copy-on-write (package: stlab-copy-on-write) was not tracked.
-- cpp-library: Dependency stlab::enum-ops (package: stlab-enum-ops) was not tracked.
-- cpp-library: Dependency acme::widgets (package: acme-widgets) was not tracked.
```

**This is expected behavior** when:
cpp-library derives each `find_dependency()` call from two sources:

- Building for development (not installing)
- Using dependencies added from subdirectories (via `CPMAddPackage` in downstream packages)
- Testing locally without installation
- **`CPMAddPackage()`**: CPM's package registry records every package and its version, whether
CPM fetches it, reuses it from `CPM_SOURCE_CACHE`, or adds it from a subdirectory.
- **`find_package()` and `FetchContent_MakeAvailable()`**: The dependency provider records calls
made after `project()`, including versions and components.

**What it means:**

- These dependencies were not captured by the dependency provider (usually because they were added in a subdirectory)
- cpp-library uses a fallback `find_dependency()` call for these dependencies
- Your build will work correctly
- If you attempt to install, validation will fail to prevent broken package configs

**When it matters:**

- **Installing the package**: Installation will fail with a detailed error, preventing broken configs
- **Not installing**: Messages are informational only - your local development builds work fine

**Solutions** (if you need to install):
The message means neither source accounts for the package that provides a linked target, for
example because the package comes from `add_subdirectory()` or from a `find_package()` call made
before `project()`.

1. **Move dependencies to top-level** (preferred):

```cmake
# In your top-level CMakeLists.txt (after project())
CPMAddPackage("gh:stlab/stlab-copy-on-write@1.1.0")
target_link_libraries(my-library INTERFACE
$<BUILD_INTERFACE:stlab::copy-on-write>
$<INSTALL_INTERFACE:$<1:stlab::copy-on-write>>)
```

2. **Manually register dependencies**:
**What it means:**

```cmake
# After adding the dependency
CPMAddPackage("gh:stlab/stlab-copy-on-write@1.1.0")
cpp_library_map_dependency("stlab::copy-on-write" "stlab-copy-on-write 1.1.0")
target_link_libraries(my-library INTERFACE
$<BUILD_INTERFACE:stlab::copy-on-write>
$<INSTALL_INTERFACE:$<1:stlab::copy-on-write>>)
```
- cpp-library uses a fallback `find_dependency(<package>)` call without a version.
- Development builds work.
- Installation fails with a detailed error, preventing a broken package config.

3. **Use CPM_USE_LOCAL_PACKAGES**: Install dependencies first, then build with local packages:
```bash
cmake -DCPM_USE_LOCAL_PACKAGES=ON -B build
```
**Solution:** Add the dependency with `CPMAddPackage()` or `find_package()` after `project()`, or
map the target explicitly:

**Why this happens:**
The dependency provider (CMake 3.24+) tracks `find_package()` and `CPMAddPackage()` calls at the project scope. When dependencies are added in subdirectories (common with transitive CPM dependencies), they aren't captured at your project's scope.
```cmake
cpp_library_map_dependency("acme::widgets" "acme-widgets 2.1.0")
```

**Important:** Ensure `cpp_library_enable_dependency_tracking()` is called before `project()` - this is required for any dependency tracking to work.
**Important:** Call `cpp_library_enable_dependency_tracking()` before `project()`; the dependency
provider must be active for `find_package()` tracking.

### CPM Repository Name Mismatch

Expand Down
75 changes: 34 additions & 41 deletions cmake/cpp-library-dependency-provider.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -220,47 +220,40 @@ function(_cpp_library_verify_quiet_dependency package_name)
endif()
endfunction()

# Track a FetchContent_MakeAvailable() call
# This is more complex because we need to extract info from prior FetchContent_Declare() calls
function(_cpp_library_track_fetchcontent)
# FetchContent_MakeAvailable can take multiple package names
foreach(package_name IN LISTS ARGN)
# Try to extract useful information from FetchContent variables
# FetchContent stores info in variables like FETCHCONTENT_SOURCE_DIR_<name>
# However, for CPM, we need different handling

# Check if this looks like a CPM-added package
# CPM sets <package>_SOURCE_DIR and <package>_VERSION
string(TOLOWER "${package_name}" package_lower)
string(TOUPPER "${package_name}" package_upper)
string(REPLACE "-" "_" package_var "${package_lower}")

# Try to get version from various places
set(VERSION "")
if(DEFINED ${package_name}_VERSION AND NOT "${${package_name}_VERSION}" STREQUAL "")
set(VERSION "${${package_name}_VERSION}")
elseif(DEFINED ${package_var}_VERSION AND NOT "${${package_var}_VERSION}" STREQUAL "")
set(VERSION "${${package_var}_VERSION}")
elseif(DEFINED ${package_upper}_VERSION AND NOT "${${package_upper}_VERSION}" STREQUAL "")
set(VERSION "${${package_upper}_VERSION}")
endif()

# Build find_dependency() call
set(FIND_DEP_CALL "${package_name}")
if(VERSION)
string(APPEND FIND_DEP_CALL " ${VERSION}")
endif()

# Store the dependency
set_property(GLOBAL PROPERTY "_CPP_LIBRARY_TRACKED_DEP_${package_name}" "${FIND_DEP_CALL}")

get_property(ALL_DEPS GLOBAL PROPERTY _CPP_LIBRARY_ALL_TRACKED_DEPS)
if(NOT package_name IN_LIST ALL_DEPS)
set_property(GLOBAL APPEND PROPERTY _CPP_LIBRARY_ALL_TRACKED_DEPS "${package_name}")
endif()

message(DEBUG "cpp-library: Tracked FetchContent(${package_name}) → find_dependency(${FIND_DEP_CALL})")
endforeach()
# Tracks one dependency made available through FetchContent_MakeAvailable()
# - Precondition: package_name is the dependency name; ARGN holds its FetchContent_Declare()
# arguments, which CMake passes to FETCHCONTENT_MAKEAVAILABLE_SERIAL providers
# - Postcondition: package_name is tracked as find_dependency(package_name [version]), where version
# comes from a <package_name>_VERSION variable when one is already set
# - Note: CPM sets <package_name>_VERSION after this call; the install module resolves the version
# of CPM packages from CPM's package registry instead
function(_cpp_library_track_fetchcontent package_name)
string(TOLOWER "${package_name}" package_lower)
string(TOUPPER "${package_name}" package_upper)
string(REPLACE "-" "_" package_var "${package_lower}")

set(VERSION "")
if(DEFINED ${package_name}_VERSION AND NOT "${${package_name}_VERSION}" STREQUAL "")
set(VERSION "${${package_name}_VERSION}")
elseif(DEFINED ${package_var}_VERSION AND NOT "${${package_var}_VERSION}" STREQUAL "")
set(VERSION "${${package_var}_VERSION}")
elseif(DEFINED ${package_upper}_VERSION AND NOT "${${package_upper}_VERSION}" STREQUAL "")
set(VERSION "${${package_upper}_VERSION}")
endif()

set(FIND_DEP_CALL "${package_name}")
if(VERSION)
string(APPEND FIND_DEP_CALL " ${VERSION}")
endif()

set_property(GLOBAL PROPERTY "_CPP_LIBRARY_TRACKED_DEP_${package_name}" "${FIND_DEP_CALL}")

get_property(ALL_DEPS GLOBAL PROPERTY _CPP_LIBRARY_ALL_TRACKED_DEPS)
if(NOT package_name IN_LIST ALL_DEPS)
set_property(GLOBAL APPEND PROPERTY _CPP_LIBRARY_ALL_TRACKED_DEPS "${package_name}")
endif()

message(DEBUG "cpp-library: Tracked FetchContent(${package_name}) → find_dependency(${FIND_DEP_CALL})")
endfunction()

# Helper function to retrieve tracked dependency information for a specific package
Expand Down
45 changes: 38 additions & 7 deletions cmake/cpp-library-install.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,28 @@ function(_cpp_library_generate_dependencies OUTPUT_VAR TARGET_NAME NAMESPACE)
endif()
endfunction()

# Returns the find_dependency() arguments for a package added through CPMAddPackage()
# - Postcondition: OUTPUT_VAR is "package_name [version]" if CPM registered package_name in this
# configuration, and empty otherwise; version is included only when CPM recorded a version of
# the form major.minor[.patch[.tweak]]
# - Note: CPM registers every added package, including packages served from CPM_SOURCE_CACHE,
# which bypass FetchContent_MakeAvailable() and therefore the dependency provider
# - Note: without an explicit VERSION, CPM derives the version from the leading digits of
# GIT_TAG (0 for a full commit hash), so an abbreviated hash or branch name yields a
# meaningless value such as "2" or "3."; omitting it is safe, emitting it is not
# - Complexity: O(n) in the number of CPM packages
function(_cpp_library_get_cpm_dependency OUTPUT_VAR package_name)
set(FIND_DEP_CALL "")
if(package_name IN_LIST CPM_PACKAGES)
set(FIND_DEP_CALL "${package_name}")
set(VERSION "${CPM_PACKAGE_${package_name}_VERSION}")
if(VERSION MATCHES "^[0-9]+(\\.[0-9]+)(\\.[0-9]+)?(\\.[0-9]+)?$")
string(APPEND FIND_DEP_CALL " ${VERSION}")
endif()
endif()
set(${OUTPUT_VAR} "${FIND_DEP_CALL}" PARENT_SCOPE)
endfunction()

# Resolve dependency using tracked provider data
# - Precondition: LIB is a target name, NAMESPACE is the project namespace
# - Postcondition: OUTPUT_VAR contains find_dependency() call syntax or error is raised
Expand Down Expand Up @@ -141,7 +163,15 @@ function(_cpp_library_resolve_dependency LIB NAMESPACE OUTPUT_VAR)

# Look up tracked dependency data
get_property(TRACKED_CALL GLOBAL PROPERTY "_CPP_LIBRARY_TRACKED_DEP_${FIND_PACKAGE_NAME}")


# A bare tracked name carries no more than CPM's registry, which also records the version
if(NOT TRACKED_CALL OR TRACKED_CALL STREQUAL FIND_PACKAGE_NAME)
_cpp_library_get_cpm_dependency(CPM_CALL "${FIND_PACKAGE_NAME}")
if(CPM_CALL)
set(TRACKED_CALL "${CPM_CALL}")
endif()
endif()

if(TRACKED_CALL)
# Found tracked data - use it directly
set(${OUTPUT_VAR} "${TRACKED_CALL}" PARENT_SCOPE)
Expand Down Expand Up @@ -175,10 +205,11 @@ function(_cpp_library_resolve_dependency LIB NAMESPACE OUTPUT_VAR)
"\n"
"The dependency provider is installed, but this dependency was not captured.\n"
"Common causes:\n"
" - find_package() or CPMAddPackage() was called in a subdirectory\n"
" - Dependency was added before project() (must be after)\n"
" - The package was added with add_subdirectory() instead of CPMAddPackage()\n"
" - find_package() was called before project() (must be after)\n"
"\n"
"Solution: Ensure dependencies are declared after project() in the top-level CMakeLists.txt.\n"
"Solution: Add the dependency with CPMAddPackage() or find_package() after project(),\n"
"or use cpp_library_map_dependency() to map the target to its package.\n"
"\n"
"Correct order:\n"
" cpp_library_enable_dependency_tracking()\n"
Expand Down Expand Up @@ -550,10 +581,10 @@ function(_cpp_library_setup_install_validation TARGET_NAME)
\"\\n\"
\"These dependencies were not captured by the dependency provider.\\n\"
\"Common causes:\\n\"
\" - find_package() or CPMAddPackage() was called in a subdirectory\\n\"
\" - Dependency was added before project() (must be after)\\n\"
\" - The package was added with add_subdirectory() instead of CPMAddPackage()\\n\"
\" - find_package() was called before project() (must be after)\\n\"
\"\\n\"
\"Solution: Ensure dependencies are declared after project() in the top-level CMakeLists.txt.\\n\"
\"Solution: Add the dependency with CPMAddPackage() or find_package() after project().\\n\"
\"Or use cpp_library_map_dependency() to manually register each dependency.\\n\"
)
endif()
Expand Down
4 changes: 4 additions & 0 deletions tests/install/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ macro(run_test TEST_NAME)
set_property(GLOBAL PROPERTY "_CPP_LIBRARY_TRACKED_DEP_${dep}")
endforeach()
set_property(GLOBAL PROPERTY _CPP_LIBRARY_ALL_TRACKED_DEPS "")

# Clear the CPM package registry
set(CPM_PACKAGES "")
endmacro()

# Helper macro to set up mock link libraries for a test target
Expand All @@ -85,6 +88,7 @@ endmacro()
# Include the actual tests
include(${CMAKE_CURRENT_LIST_DIR}/test_dependency_mapping.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/test_dependency_provider.cmake)
include(${CMAKE_CURRENT_LIST_DIR}/test_cpm_registry.cmake)

# Print summary
message(STATUS "")
Expand Down
Loading
Loading