What is the purpose of a .cmake file?

Viewed 24739

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 ?

3 Answers

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.

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

CMake input files are written in the "CMake Language" in source files named CMakeLists.txt or ending in a .cmake file name extension. https://cmake.org/cmake/help/latest/manual/cmake-language.7.html

This means they're one and the same thing. "CMakeLists.txt" is simply the default name. If you decide to split the code (CMake is technically just another interpreted language) into separate files/modules (that you can include into each other), they obviously can't all have the same name, so you would use the ".cmake" extension. Theoretically, you could call "CmakeLists.txt" as "CmakeLists.cmake", but then cmake won't be able to find it by default, so you'd have to pass the filename as a command-line argument. So it is just a difference of naming conventions. Everything you can put in one file, you can put in the other, and vice-versa.

Related