Basics of CMake

CMake is a cross-platform build configuration system for C and C++ among others. This blog is about the basics of CMake.

To set up CMake we use a plain text file called CMakeLists.txt. The file name is case sensitive on Linux. The commands in CMakeLists.txt are case insensitive.

This is a basic CMakeLists.txt:

cmake_minimum_required(VERSION 3.0 LANGUAGES C CXX ASM)
project (projectname VERSION 0.1.0)
add_executable(myexecutable main.cpp)

If you have a higher version that 3.0, you can use that but you are expecting everyone to have that version. Linux distributions like Debian are likely to be quite a way behind distributions like Tumbleweed and Arch. Use the minimum required versions for the cmake features you use.

The project line isn’t mandatory but it’s a good idea to put the name and version of your project. The add_executable specified the executable name followed by all the source files, in this case main.cpp. Use what white-space makes sense.

To build the project run cmake to generate the makefiles and make to actually build the project.

cmake .
make

However, this will clutter your source tree with build files. A better approach is to create a build directory and run cmake from there. From your project directory:

mkdir build
cd build
cmake ..
make

Notice the two dots after the cmake command. This means build the parent directory.

CMake can also build libraries instead of executable programs by using add_library instead of add_executable:

add_library(libraryname STATIC main.cpp other.cpp)
target_link_libraries(myexecutable libraryname)

We can build both libraries and executables by specifying both add_executable and add_library with the appropriate sources. The other option instead of static is shared to build a shared library. You can use Ninja as your build tool by specifying the appropriate flag to cmake:

cmake -G ninja ..
ninja

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.