Cmake Tutorial To Build and Compile In Linux

Binaries are created by building or compiling source like C, C++ etc. In simple applications we can build by using the compiler like gcc directly. But this is inconvenient if the application is big and have a lot of source code, configuration file and build options. Developers generally prefers build systems like make but there is alternative named cmake which is popular in Linux ecosystem too.


CMake is an extensible and opensource build manage software.


We can install CMake for different Linux distributions with the following commands.

Ubuntu, Debian, Mint, Kali

$ sudo apt-get install cmake
CMake Installation
CMake Installation

Fedora, CentOS, RHEL

$ sudo yum install cmake

Example Application

In order to compile an application we need some source code. We will use following source code which is written in C++ and have very basic logic. But as stated before CMake is designed to be used complex build processes.

#include <iostream>

using namespace std;

int main(void) {

cout << "Hello World" << endl;



Global Variables

CMake is very extensible and flexible build system where we can specify a lot of different options and variables. We will explain some of them below.


This variable is used to specify the binary files directory which is generally same as CMAKE_SOURCE_DIR .


This variables is used to specify the source directory where the source code and other related configurations resides.


After the compile operation the created executable file will be written to the specified directory.


If we want to create libraries in a separate path we can use this variable where all created libraries will be put.

LEARN MORE  How To Compile Linux Kernel From Source Code?

Example CMake Configuration

We will create a sample configuration file to build given example named app.cpp . We will use following configuration which is very simple. We will name the configuration CMakeList.txt and this file will be automatically interpreted by CMake.

cmake_minimum_required(VERSION 3.9)

add_executable(hello ${PROJECT_SOURCE_DIR}/app.cpp)

Build with Cmake

We will run cmake command and provide the directory path where CMakeLists.txt configuration file resides.

$ cmake .
Build with Cmake
Build with Cmake

Leave a Comment