I’ve used conan and vcpkg with varying levels of success. Recently, I came across CPM.cmake and it works quite well with the projects I have used it in.
For getting CPM.cmake in your own CMake project, you have to download the CPM.cmake code:
project(your_project_name LANGUAGES CXX)
cmake_minimum_required(VERSION 3.24)
# Download CPM.cmake
file(
DOWNLOAD
https://github.com/cpm-cmake/CPM.cmake/releases/download/v0.40.8/CPM.cmake
${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake
EXPECTED_HASH SHA256=78ba32abdf798bc616bab7c73aac32a17bbd7b06ad9e26a6add69de8f3ae4791
)
include(${CMAKE_CURRENT_BINARY_DIR}/cmake/CPM.cmake)The above code will download the CMake module and after that, you can bring in libraries, like Catch2:
# ---- Dependencies ----
CPMAddPackage("gh:catchorg/Catch2@3.4.0")There are examples of how to use the CPMAddPackage function call, in folder https://github.com/cpm-cmake/CPM.cmake/tree/master/examples
Sometimes, I found, that not all libraries set up properly without a little extra help. Here’s an example:
CPMAddPackage("gh:nothings/stb#master")
add_library(stb INTERFACE)
target_include_directories(stb INTERFACE ${stb_SOURCE_DIR})The above project just brings in the header files, and I use the add_library and target_include_directories CMake functions to create an INTERFACE target that can be used by the projects that need it.
Another example, which has a Config file for CMake, is:
CPMAddPackage("gh:Dav1dde/glad#v2.0.6")
# Bring in this folder so we get access to the glad_add_library function
add_subdirectory("${glad_SOURCE_DIR}/cmake" glad_cmake)
glad_add_library(glad
REPRODUCIBLE
EXCLUDE_FROM_ALL
LOADER
API gl:core=4.6
EXTENSIONS
GL_ARB_bindless_texture
GL_EXT_texture_compression_s3tc
)
So like that, you can use CPM.cmake to download dependencies into your CMake project.