Let's assume we have a very basic C++ project, with the following directory structure:
shell/project /src main.cpp CMakeLists.txt
In this project, main.cpp is the only source file, with the following content:
cpp#include <iostream> int main() { std::cout << "Hello, CMake!" << std::endl; return 0; }
Next, our CMakeLists.txt file, located in the project root, defines how to build the project. The content of this file will be:
cmakecmake_minimum_required(VERSION 3.10) # Specifies the minimum required CMake version project(HelloCMake) # Defines the project name add_executable(hello_cmake src/main.cpp) # Creates an executable named hello_cmake with source file src/main.cpp
This CMake configuration file first sets the minimum required version of CMake, which is crucial for ensuring consistent builds. Next, it defines the project name, which aids in project management and identification. Finally, it uses the add_executable command to specify how the executable should be generated. Here, hello_cmake is the name of the generated executable, and src/main.cpp is the source file it depends on.
To build this project, you need to run the following CMake commands in the project root directory:
bashcmake -S . -B build # Generates the build system cmake --build build # Builds the project
These commands first generate the build system, specifying that the generated files are placed in the build directory. The second command then compiles the code to generate the executable.
After completing these steps, you can find the hello_cmake executable in the build directory. Running it will produce the output:
shellHello, CMake!
This example demonstrates how to build a very simple C++ program using CMake, suitable for beginners and quick builds of small projects.