CMake Tutorial To Build and Compile In Linux – POFTUT

CMake Tutorial To Build and Compile In Linux


Binaries are created by building or compiling sources 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 has a lot of source code, configuration file, and build options. Developers generally prefer to build systems like make but there is an alternative named CMake which is popular in the Linux ecosystem too.

About cmake Command

CMake is an extensible and opensource build manage software.

cmake Installation

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 the 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;

  return(0);
}

cmake Global Variables

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

CMAKE_BINARY_DIR

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

CMAKE_SOURCE_DIR

This variable is used to specify the source directory where the source code and other related configurations reside.

EXECUTABLE_OUTPUT_PATH

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

LIBRARY_OUTPUT_PATH

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

LEARN MORE  Pip ffi.h Gcc Error

Example CMake Configuration

We will create a sample configuration file to build a given example named app.cpp . We will use the 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 .

Leave a Comment