How to properly import CMake files/modules?

One of the drawbacks to rolling out your CMake files to each developer machine and then loading them with include() is that those CMake files sit outside of version control. If you change those CMake files, your project loses traceability, meaning that you cannot reliably build an earlier version of the project because these CMake file dependencies are not traceable.

Let me suggest a different alternative. Consider whether you can have the project download those CMake files on-demand using the FetchContent module instead. You put the CMake files in their own git repository or whatever version control system you prefer to use. In the project, you specify exactly the git hash of the commit to retrieve in the FetchContent_Declare() command. Now the project has full traceability of the CMake files, since the git hash is included in the project’s own sources. As an added benefit, you no longer need any separate infrastructure to roll out your CMake files to developer machines ahead of time.

  • If needed, you can use FetchContent before the first project() call to retrieve part or all of the toolchain being used to build the project.
  • FetchContent avoids communicating with the remote end if it knows it doesn’t need to. If you use a git hash for the GIT_TAG, then it can tell if it already has the commit it needs and will use it without needing to do a git fetch. Developers can therefore work offline after the first run has downloaded the required commit from your repo.
  • You can make including the CMake files part of the fetched repo. The FetchContent_MakeAvailable() command will call add_subdirectory() on the fetched repo’s source directory if there is a CMakeLists.txt file at the top level. You can put whatever commands you want in that CMakeLists.txt file, so you have an injection point to pull in CMake files with include() to define commands, etc.

I recommend you take a look at the FetchContent module documentation to get an idea of how it works and what you can do with it.

1 Like