Install CMake on Ubuntu 24.04

Install CMake on Ubuntu 24.04

CMake is a tool which uses a configuration file called CMakeLists.txt for generating standard build files such as makefiles on Unix systems, Visual Studio project files on Windows, etc. CMake is not a compiler or build system, but rather it generates build files that can be used to compile source code.

This tutorial demonstrates how to install CMake on Ubuntu 24.04.

Install CMake

Download GPG key:

sudo wget -qO /etc/apt/trusted.gpg.d/kitware-key.asc https://apt.kitware.com/keys/kitware-archive-latest.asc

Add repository:

echo "deb https://apt.kitware.com/ubuntu/ $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/kitware.list

Next, update the package lists:

sudo apt update

Run the following command to install CMake:

sudo apt install -y cmake

Once installation is completed, we can check CMake version:

cmake --version

Testing CMake

Create a new directory for storing project files and navigate to this directory:

mkdir helloworld && cd helloworld

Create a main.c file:

nano main.c

Add the following code:

helloworld/main.c

#include <stdio.h>

int main() {
    printf("Hello world\n");

    return 0;
}

Next, create CMake configuration file called CMakeLists.txt:

nano CMakeLists.txt

Once the file is opened, add the following content:

helloworld/CMakeLists.txt

cmake_minimum_required(VERSION 3.0)
project(hello C)

add_executable(hello main.c)

Recommended creating separate directory for storing files which will be generated by CMake.

mkdir build && cd build

Here is a project structure:

helloworld/
    build/
    CMakeLists.txt
    main.c

Run the cmake command in a build directory to generate build files using CMakeLists.txt file that located in parent directory. By default, CMake will generate build files for the native build system. In our case, it will be makefiles.

cmake ..

When finished, the ls command can be used to list files in a directory.

CMakeCache.txt  CMakeFiles  cmake_install.cmake  Makefile

As we can see, the Makefile file has been generated. Now run the make command to build program:

make

Run a program:

./hello

Uninstall CMake

If you want to completely remove CMake, execute the following command:

sudo apt purge --autoremove -y cmake

You can also remove related dependencies:

sudo apt purge --autoremove -y cpp make binutils

Remove GPG key and repository:

sudo rm -rf /etc/apt/trusted.gpg.d/kitware-key.asc
sudo rm -rf /etc/apt/sources.list.d/kitware.list

Leave a Comment

Cancel reply

Your email address will not be published.