CMake Practical Guide (Part One)

CMake Practical Guide (Part One)

Click the blue text above to follow us

CMake Practical Guide (Part One)
CMake Practical Guide (Part One)

Introduction

Previously, we introduced the use of Autotools; today we will look at how to use CMake. CMake is a project build tool, similar to Autotools. It can be simply understood as a tool that helps us generate Makefiles for easier compilation.

CMake Practical Guide (Part One)
CMake Practical Guide (Part One)

Usage Example

(1) Create main.c, hello.c, and hello.h files with the following content:

//hello.c
#include <stdio.h>
#include "hello.h"
int printHello(void) {
    printf("Hello, World\n");
}
//hello.h
#ifndef _HELLO_H
#define _HELLO_H
int printHello(void);
#endif
//main.c
#include <stdio.h>
#include "hello.h"
int main(void) {
    printHello();
    return 0;
}

(2) Create CMakeLists.txt with the following content:

# Minimum CMake version requirement. If this line is not included, a warning will be shown.
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
PROJECT(HELLO) # Project name
# Add all source files in the current directory (.) to the variable SRC_LIST
AUX_SOURCE_DIRECTORY(. SRC_LIST)
# Generate the executable hello
ADD_EXECUTABLE(hello ${SRC_LIST})

CMAKE_MINIMUM_REQUIRED: Specifies the minimum required version of CMake

PROJECT: Specifies the project name

AUX_SOURCE_DIRECTORY: Adds source file list

ADD_EXECUTABLE: Generates the executable

(3) Create a build directory

mkdir build

The directory structure is as follows:

CMake Practical Guide (Part One)

Creating a build directory is to keep some intermediate files in that directory to avoid clutter; it can also be omitted.

(4) Use cmake to build the project

cd build
cmake ..     // .. indicates the parent directory

If cmake is not installed, use the following command to install it:

sudo apt-get install cmake

CMake Practical Guide (Part One)

After successful execution, a Makefile will be generated

CMake Practical Guide (Part One)

(5) Compile to generate the executable file

make

CMake Practical Guide (Part One)

CMake Practical Guide (Part One)
CMake Practical Guide (Part One)

Conclusion

After the simple example above, do you feel that CMake is simpler than Autotools? The main work is writing the CMakeLists.txt. More command rules can be found in the official documentation!

Official Documentation:

https://cmake.org/cmake/help/v3.19/manual/cmake-commands.7.html

CMake Practical Guide (Part One)
Wonderful Recommendations
High-Precision Timers in Linux Kernel
Year-End Summary
Introduction to Autotools

CMake Practical Guide (Part One)

Long pressto scan the QR code in the imageto follow

Leave a Comment