How to do it

Alongside the source file, we need to provide CMake with a description of the operations to perform to configure the project for the build tools. The description is done in the CMake language, whose comprehensive documentation can be found online at https://cmake.org/cmake/help/latest/. We will place the CMake instructions into a file called CMakeLists.txt

The name of the file is case sensitive; it has to be called  CMakeLists.txt for CMake to be able to parse it.

In detail, these are the steps to follow:

  1. Open a text file with your favorite editor. The name of this file will be CMakeLists.txt.
  2. The first line sets a minimum required version for CMake. A fatal error will be issued if a version of CMake lower than that is used:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
  1. The second line declares the name of the project (recipe-01) and the supported language (CXX stands for C++):
project(recipe-01 LANGUAGES CXX)
  1. We instruct CMake to create a new target: the executable hello-world. This executable is generated by compiling and linking the source file hello-world.cpp. CMake will use default settings for the compiler and build automation tools selected:
add_executable(hello-world hello-world.cpp)
  1. Save the file in the same directory as the source file hello-world.cpp. Remember that it can only be named CMakeLists.txt.
  2. We are now ready to configure the project by creating and stepping into a build directory:
$ mkdir -p build
$ cd build
$ cmake ..

-- The CXX compiler identification is GNU 8.1.0
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/user/cmake-cookbook/chapter-01/recipe-01/cxx-example/build
  1. If everything went well, the configuration for the project has been generated in the build directory. We can now compile the executable: 
$ cmake --build .

Scanning dependencies of target hello-world
[ 50%] Building CXX object CMakeFiles/hello-world.dir/hello-world.cpp.o
[100%] Linking CXX executable hello-world
[100%] Built target hello-world