CMake Quick Start

What is CMake

  • CMake is an open-source, cross-platform family of tools designed to build, test and package software.
  • CMake is used to control the software compilation process using simple platform and compiler independent configuration files, and generate native makefiles and workspaces that can be used in the compiler environment of your choice.
  • You can imagine CMake as a tool for generating native makefiles for your C/C++ projects

Key commands in CMakeLists.txt

  • cmake_minimum_required: specify minimum cmake version
  • project: project name
  • set: set variables or flags
  • file: can use glob to locate all source files
  • add_executable: specify the executable name and all files that need to be built

A HelloWorld example

  • Example Project Structure:

    1
    2
    3
    4
    5
    .
    ├── CMakeLists.txt
    ├── build
    └── src
    └── helloworld.cpp
  • An example CMakeLists.txt can be:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    cmake_minimum_required(VERSION 3.0)

    project(HelloWorld)

    set (source_dir "${PROJECT_SOURCE_DIR}/src/")

    file (GLOB source_files "${source_dir}/*.cpp")

    add_executable(HelloWorld ${source_files})
  • put cpp source files into src folder, put CMakeLists.txt under root folder, then create a empty build folder(so that all build files will be inside the build folder, not in the root folder).

  • go into build folder cd build, and then generate makefile using cmake .., you will see makefile in the build folder.

  • use make to build the executable, and use ./HelloWorld to run the executable.