Writing Our Own Find-Modules
Let's learn how to write and find custom package in CMake.
We'll cover the following...
On a rare occasion, the library we want to use in our project doesn't provide a config-file or a PkgConfig file, and there's no find-module readily available in CMake already. We can then write a custom find-module for that library and ship it with our project. This situation is not ideal, but in the interest of taking care of the users of our project, it has to be done.
Example
Since we have already become familiar with libpqxx
in the previous section, let's write a nice find-module for it. We start by writing in a new FindPQXX.cmake
file, which we'll store in the cmake/module
directory of our project source tree. We need to make sure that the find-module gets discovered by the CMake when find_package()
is called, so we'll add this path to the CMAKE_MODULE_PATH
variable in our CMakeLists.txt
with list(APPEND)
. The whole list file should look like this:
cmake_minimum_required(VERSION 3.25.1)project(FindPackageCustom CXX)list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake/module/")find_package(PQXX REQUIRED)add_executable(main main.cpp)target_link_libraries(main PRIVATE PQXX::PQXX)
Now that that's done, we need to write the actual find-module. Technically speaking, nothing will happen if the FindPQXX.cmake
file is empty: CMake won't complain if some specific variables aren't set (including PQXX_FOUND
), even if a user calls find_package()
with REQUIRED
. It's up to the author of the find-module to respect conventions outlined in CMake's documentation:
CMake will provide a
<PKG_NAME>_FIND_REQUIRED
variable set to1
whenfind_package(<PKG_NAME> REQUIRED)
is called. A find-module should callmessage(FATAL_ERROR)
when a library is not found. ...