[CMake] What is the best practice for installing custom CMake modules?

Timothy Wrona tjwrona1992 at gmail.com
Mon Feb 11 15:27:00 EST 2019


I've written a custom CMake module (MyModule.cmake) and would like to
install it in a sensible location on my system so my other CMake projects
can find it easily.

First of all, is there an accepted standard way of doing this?
If not, is my approach below acceptable and considered good practice?

I have taken the following approach:

*Project structure:*

MyModule
    |---CMakeLists.txt
    |---MyModule.cmake
    |---MyModuleConfig.cmake

*Contents of CMakeLists.txt:*

cmake_minimum_required(VERSION 3.13.0)

project(MyModule)

install(
  FILES
    ${CMAKE_CURRENT_SOURCE_DIR}/MyModuleConfig.cmake
    ${CMAKE_CURRENT_SOURCE_DIR}/MyModule.cmake
  DESTINATION
    share/cmake/${PROJECT_NAME}
)

*Contents of MyModule.cmake:*

message(STATUS "included: my-module.cmake")

*Contents of MyModuleConfig.cmake*

# Add this module's directory to the "CMAKE_MODULE_PATH" so it is visible
after calling "find_package()"
list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR})

--------------------------------
The module can easily be built and installed with the following commands:

cmake -S . -B build
cmake --build build --target install

--------------------------------
Once installed, the module can be used in any future CMake project as
follows:

find_package(MyModule)
include(MyModule)

This approach seems to work quite well and is very easy to use, but I feel
like modifying "CMAKE_MODULE_PATH" from "MyModuleConfig.cmake" is not
really a standard way of doing things because I've never seen it done
before.

Is this approach considered okay? Or is there a better more accepted way to
easily make your own CMake modules visible from other projects?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://cmake.org/pipermail/cmake/attachments/20190211/fb8da495/attachment.html>


More information about the CMake mailing list