Introduction to CMake Basics

This article mainly refers to this link.

1. CMake Compilation Principles

CMake is a cross-platform build tool that is more advanced than make and much easier to use. CMake primarily involves writing a CMakeLists.txt file and then using the cmake command to convert it into a makefile required by make. Finally, the make command compiles the source code to generate executable programs or shared libraries (so). Therefore, the CMake compilation process essentially consists of two steps:

cmake

make

The cmake command points to the directory where the CMakeLists.txt file is located. For example, cmake .. indicates that CMakeLists.txt is in the parent directory of the current directory. The cmake command will generate many intermediate files and a makefile, so it is generally recommended to create a new directory specifically for building, such as:

mkdir build

cd build

cmake ..

make

The make command compiles the program based on the generated makefile.

2. Using CMake to Compile a Program

We will write a C/C++ program project about calculating the square root, specifically b = sqrt(a), to understand the entire CMake compilation process.

Step 1: Create the project directory:

$ mkdir m_sqrt
$ cd m_sqrt/
$ mkdir build include src
$ touch CMakeLists.txt README

After this, your project directory should look like this:

Introduction to CMake Basics

Step 2: Start configuring this project

Run $ gedit CMakeLists.txt in the terminal and paste the following code:

Write the CMakeLists.txt file, which should be placed in the same level directory as src and include. It can actually be anywhere, as long as the paths written inside correctly point to the right locations. The CMakeLists.txt mainly contains the following seven steps; for specific meanings, please read the corresponding comments.

Introduction to CMake Basics

Step 3: Write the code

Header file b.h, as shown below:

Introduction to CMake Basics

Header file b.c, as shown below:

Introduction to CMake Basics

Main function main.c, as shown below:

Introduction to CMake Basics

Step 4: Compile and run the program

Make sure to enter the build directory

cd build
cmake ..
make

After compilation, an executable file test_sqrt is generated in the build directory. Run it to get the following result:

Introduction to CMake Basics

Command:

./test_sqrt

Result:

input a: 49.000000

sqrt result: 7.000000

Press and hold the image below to follow the share space public account,there are a lot of materials and practical tutorials waiting for you. Every like and share is our greatest support.

Introduction to CMake Basics

Leave a Comment