CMake Build Example
This article uses a complete C++ project to show how to build a project containing an executable and a library from scratch with CMake.
The example contains a main program and a custom library, covering the full CMake build lifecycle.
Project preparation
Before building, create the project files and understand the project structure.
Project Structure
The example has a main program source file, a library source file and a library header; 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 program entry point |
src/mylib.cpp |
Library source file | Implementation of the custom library's features |
include/mylib.h |
Library header file | Declaration of the library's public interface, included by the main program |
The CMakeLists.txt configuration file
Create CMakeLists.txt in the MyProject root directory with the following content:
Example
File path: MyProject/CMakeLists.txt
Specify the minimum CMake version (must be the first line)
cmake_minimum_required
(
VERSION
3.10
)
Define the 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 a global header search path
include_directories
(
$
{
PROJECT_SOURCE_DIR
}
/
include
)
Create the library target MyLib (source file src/mylib.cpp)
add_library
(
MyLib src
/
mylib.
cpp
)
Create the executable target MyExecutable (source file src/main.cpp)
add_executable
(
MyExecutable src
/
main.
cpp
)
Link the MyLib library into the MyExecutable executable
target_link_libraries
(
MyExecutable MyLib
)
Here is what each command in the configuration file does:
| Instruction | Purpose | Key points |
|---|---|---|
cmake_minimum_required(VERSION 3.10) |
Specify the minimum CMake version | Must be at the very top of the file; an older version reports an error |
project(MyProject VERSION 1.0) |
Define the project name and version | The version number sets variables such as PROJECT_VERSION |
set(CMAKE_CXX_STANDARD 11) |
Specify the C++ standard | Combined with CMAKE_CXX_STANDARD_REQUIRED to enforce it |
include_directories(...) |
Add header search paths | Lets the compiler find headers under include/ |
add_library(MyLib ...) |
Create a library target | With no type specified, BUILD_SHARED_LIBS decides static or shared |
add_executable(MyExecutable ...) |
Create the executable target | The target name becomes the name of the generated executable |
target_link_libraries(...) |
Link a library to an executable | MyExecutable automatically links MyLib when compiled |
Every add_executable and add_library defines abuild target (Target). The target concept is central to CMake: later commands such as target_include_directories and target_link_libraries are all organized around targets.
Build steps explained
With CMakeLists.txt in place, complete the build and run in the following six steps.
Overview of the whole process:
| Step | Operation | Command |
|---|---|---|
| 1 | Create CMakeLists.txt | Write the configuration file manually |
| 2 | Create the build directory | mkdir build && cd build |
| 3 | Configure the project | cmake .. |
| 4 | Compile the project | make or cmake --build . |
| 5 | Run the executable | ./MyExecutable |
| 6 | Clean up build files | make clean |
Create the CMakeLists.txt file
Create CMakeLists.txt in the MyProject root directory; its content was given in the previous section.
This is the starting point of the whole CMake build; all build rules are defined in this file.
Create the build directory
To keep the source tree clean, the recommended approach is an out-of-source build: create a separate build directory under the project root.
Open a terminal and enter the MyProject directory:
# Create build directory
mkdir build
# Change into the build directory (all subsequent operations will be executed in this directory)
cd build
Add the build directory to .gitignore so build artifacts are not committed to version control.
Configure the project
Run CMake in the build directory to generate build system files suitable for the current platform (such as a Makefile).
.. points to the source directory containing CMakeLists.txt.
# Run CMake configuration in the build directory
cmake ..
CMake prints configuration results showing the detected compiler and configuration status. If everything is fine you will see output similar to this:
-- 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 an error occurs during configuration (for example a missing compiler or a CMake version that is too old), CMake stops and prints the specific reason. After fixing the problem, rerun
cmake ...
Compile the project
Once the build files are generated, compile the project with the corresponding build command.
By default CMake generates a Makefile on Unix-like systems, so the make command can be used directly.
# Compile the project in the build directory
make
After compilation the build directory contains the executable MyExecutable and the library file libMyLib.a.
You can also use the cross-platform generic build command:
# cmake --build . will automatically call the correct underlying build tool
cmake --build .
Run the executable
After a successful build, run the generated executable directly from the build directory.
# Run the compiled executable
./MyExecutable
# Expected output example
Hello from RUNOOB! This is MyLib speaking.
Clean up build files
Cleaning deletes intermediate files (.o files and so on) and target files produced during compilation, freeing disk space.
Use the make clean command:
# Remove intermediate and object files generated by compilation
make clean
Delete the build directory manually:
If no clean rule is defined, you can simply delete the entire build directory.
# Go back to the project root directory and delete the build directory
cd ..
rm -rf build
Deleting the whole build directory is the most thorough cleanup. For the next build just rerun mkdir build && cd build && cmake .. && make from scratch.
Notes
Make sure source file paths are correct.Source paths in add_executable and add_library are relative to the directory containing CMakeLists.txt. A wrong path does not fail at configure time, but the compiler reports a missing file.
Target names are case sensitive.MyLib and mylib are different targets. The target name referenced in target_link_libraries must exactly match the one defined by add_library.
Reconfigure after changing CMakeLists.txt.If only source files changed, just run make; but if CMakeLists.txt changed (for example adding a new file or changing compile options), rerun cmake .. or run cmake --build . (which detects configuration changes automatically).
Beginners should start with a simple project.First get the whole build flow working with a single executable, then gradually add libraries, external dependencies and custom compile options. Adding too much at once makes debugging hard.