CMake Build Example

This article uses a complete C++ project example to demonstrate how to use CMake to build a project containing both executable files and library files from scratch.

The example project includes a main program and a custom library, covering the complete lifecycle of a CMake build.


Project Preparation

Before starting the build, first create the project files and understand the project structure.

Project Structure

The example project includes a main program source file, a library source file, and a library header file. The directory structure is as follows:

MyProject/
├── CMakeLists.txt          # CMake 配置文件
├── src/
│   ├── main.cpp            # 主程序源文件
│   └── mylib.cpp           # 库源文件
└── include/
    └── mylib.h             # 库头文件
File Purpose Description
CMakeLists.txt CMake configuration file Defines the project's build rules, targets, and dependencies
src/main.cpp Main program source file Contains the main() function, the entry point of the program
src/mylib.cpp Library source file Implementation of the custom library's functionality
include/mylib.h Library header file Declares the library's public interface for the main program to include and use

CMakeLists.txt Configuration File

Create a CMakeLists.txt file in the MyProject root directory and write the following content:

Example

# File path: MyProject/CMakeLists.txt

# Specify the minimum CMake version (must be placed on the first line of the file)
cmake_minimum_required(VERSION 3.10)

# Define project name and version number
project(MyProject VERSION 1.0)

# Set the C++ standard to C++11 and require the compiler to enforce it
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# Add global header file search path
include_directories(${PROJECT_SOURCE_DIR}/include)

# Create library target MyLib (source file: src/mylib.cpp)
add_library(MyLib src/mylib.cpp)

# Create executable target MyExecutable (source file: src/main.cpp)
add_executable(MyExecutable src/main.cpp)

# Link the MyLib library to the MyExecutable executable
target_link_libraries(MyExecutable MyLib)

The function of each directive in the configuration file is as follows:

Directive Function Key Point
cmake_minimum_required(VERSION 3.10) Specify minimum CMake version Must be placed at the very top of the file; versions below this will cause an error
project(MyProject VERSION 1.0) Define project name and version The version number sets variables such as PROJECT_VERSION
set(CMAKE_CXX_STANDARD 11) Specify C++ standard Use with CMAKE_CXX_STANDARD_REQUIRED to ensure it is enforced
include_directories(...) Add header file search path Enables the compiler to find header files under include/
add_library(MyLib ...) Create library target When no type is specified, BUILD_SHARED_LIBS determines whether it is static or dynamic
add_executable(MyExecutable ...) Create executable target The target name will be used as the final generated executable file name
target_link_libraries(...) Link library to executable MyExecutable will automatically link MyLib during compilation

Each add_executable and add_library defines abuild target (Target).The concept of targets is the core of CMake—subsequent commands such as target_include_directories, target_link_libraries, etc., are all organized around targets.


Detailed Build Steps

With CMakeLists.txt in place, complete the project build and run in the following six steps.

Overall process overview:

Step Operation Command
1 Create CMakeLists.txt Manually write the configuration file
2 Create build directory mkdir build && cd build
3 Configure project cmake ..
4 Build project makeorcmake --build .
5 Run executable ./MyExecutable
6 Clean build files make clean

Create CMakeLists.txt File

Create the CMakeLists.txt file in the MyProject root directory; its contents were provided in the configuration instructions of the previous section.

This is the starting point of the entire CMake build; all build rules are defined in this file.

Create Build Directory

To keep the source code directory clean, it is recommended to useOut-of-sourcethe out-of-source build approach—create a separate build directory under the project root.

Open a terminal and navigate to the MyProject directory:

# 创建构建目录
mkdir build

# 进入构建目录(后续所有操作都在此目录执行)
cd build

Add the build directory to the .gitignore file to avoid committing build artifacts to version control.

Configure Project

Run CMake in the build directory to generate build system files (e.g., Makefile) suitable for the current platform.

..Point to the source directory containing CMakeLists.txt.

# 在 build 目录中运行 CMake 配置
cmake ..

CMake will output the configuration results, showing the detected compiler and configuration status. If everything goes well, you will see output similar to the following:

-- The CXX compiler identification is GNU 11.4.0
-- Detecting CXX compiler ABI info - done
-- Configuring done
-- Generating done
-- Build files have been written to: /path/to/MyProject/build

If errors occur during configuration (such as a missing compiler or a CMake version that is too old), CMake will abort and output the specific error reason. After resolving the corresponding issue, re-runcmake ..and that's it.

Compile Project

After the build files are generated, use the corresponding build command to compile the project.

By default, CMake generates Makefiles on Unix-like systems, so you can directly use the make command.

# 在 build 目录中编译项目
make

Once compilation is complete, the executable MyExecutable and the library file libMyLib.a will be generated in the build directory.

You can also use the cross-platform generic build command:

# cmake --build . 会自动调用正确的底层构建工具
cmake --build .

Run Executable

After a successful build, run the generated executable directly in the build directory.

# 运行编译生成的可执行文件
./MyExecutable

# 预期输出示例
Hello from EXAMPLE! This is MyLib speaking.

Clean Build Files

The clean operation deletes intermediate files (.o files, etc.) and target files generated during compilation, freeing up disk space.

Use the make clean command:

# 删除编译产生的中间文件和目标文件
make clean

Manually delete the build directory:

If no clean rules are defined, you can simply delete the entire build directory.

# 回到项目根目录,删除 build 目录
cd ..
rm -rf build

Deleting the entire build directory is the most thorough way to clean. For the next build, simply re-run mkdir build && cd build && cmake .. && make to start from scratch.


Notes

Ensure the source file paths are correct.The source file paths in add_executable and add_library are relative to the directory where CMakeLists.txt is located. If the paths are incorrect, the CMake configuration stage won't report an error, but the compilation will complain that the files cannot be found.

Target names are case-sensitive.MyLib and mylib are different targets. The target names referenced in target_link_libraries must exactly match the target names defined in add_library.

Reconfiguration is required after modifying CMakeLists.txt.If you only modified source files, simply run make; but if you modified CMakeLists.txt (such as adding new files or changing compile options), you need to re-run cmake .. or directly run cmake --build . (it will automatically detect configuration changes).

For first-time users, it is recommended to start with a simple project.First get the entire build flow working with a single executable, then gradually add libraries, external dependencies, and custom compile options. Adding too many things at once will make it harder to troubleshoot errors.

Other extensions