51

I might be googling wrongly, but I'm unable to find what's the purpose of .cmake files.

I've just stumbled across the CMake tool for a project I've to work with and I'm having a hard time to understand how it works. I do understand that running the CMake command in a directory containing a CMakeLists.txt executes the commands in that file (along with the commands in the CMakeLists.txt contained in the sub-directories) but the purpose of .cmake files is a lot more fuzzy.

It seems that they are used to define functions/set variables that are thereafter used in the CMakeLists.txt but I'm not sure. How are they used by the CMake tool ?

2 Answers 2

42

You can include it with the include command. Similar to how other languages allow you to split source files into modules or header files, they can contain function definitions, macros which can then be reused across multiple CmakeLists.

See https://cmake.org/cmake/help/v3.0/command/include.html

Note that you can actually include any file, but a .cmake extension is commonly used.

2
  • 2
    Further to this, often .cmake files are bundled with modules to provide some scriptable functionality. Often called via the -P ... mechanism.
    – user1531971
    Commented Sep 27, 2017 at 20:27
  • I am not quite sure that all .cmake files are always include files, some of them seem to be executed like scripts. For example in a build I'm doing with Visual Studio, it calls cmake.exe" -DBUILD_TYPE=$(Configuration) -P cmake_install.cmake. Is a .cmake file kind of assumed to be an internal file (i.e., one that's generated by a script rather than one that you edit directly?), though that theory doesn't hold, either, because CMakeCache has the extension .txt.
    – jrh
    Commented Mar 3, 2020 at 23:29
17

Within this file you can define functions of macros which can be used in your CMakeLists.txt file. But there are some more other applications for .cmake files. For example if you want to provide a library or tool they should at least contain a <name>Config.cmake so that your library can be used with the find_package() command. Further information can be found in CMake Wiki

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.