CMake is widely used in modern software development for managing builds across different platforms. Learning to set up a CMake project is essential for developing applications efficiently. This step-by-step guide will help you create a basic CMake project.
Prerequisites
Before you start, ensure you have the following: - A C++ compiler (like GCC, Clang, or MSVC) - CMake installed on your system (download here) - A text editor or IDE of your choice
Step 1: Create Project Structure
Start by creating the directory structure for your project. This helps keep the project organized.
1 2 3 |
mkdir MyCMakeProject cd MyCMakeProject mkdir src |
Step 2: Write the C++ Code
Create a simple C++ program in the src
directory.
src/main.cpp
1 2 3 4 5 6 |
#include <iostream> int main() { std::cout << "Hello, CMake World!" << std::endl; return 0; } |
Step 3: Create a CMakeLists.txt File
The CMakeLists.txt
file is the core of your project configuration. Create it in the root of your project directory.
CMakeLists.txt
1 2 3 4 5 6 7 8 |
cmake_minimum_required(VERSION 3.18) project(MyCMakeProject) # Specify the C++ standard set(CMAKE_CXX_STANDARD 17) # Add the executable target add_executable(MyCMakeProject src/main.cpp) |
Step 4: Generate Build Files
With your CMakeLists.txt
file in place, you can now generate the build files for your project.
1
|
cmake -S . -B build
|
This command configures the project and places the build files in a directory named build
.
Step 5: Build the Project
Navigate to the build directory and compile the project.
1
|
cmake --build build
|
This will compile your source code and create an executable.
Step 6: Run the Executable
After a successful build, run the executable to see the output.
1
|
./build/MyCMakeProject
|
You should see the output: Hello, CMake World!
Additional Resources
To deepen your understanding of CMake and explore advanced features, check out these tutorials:
- How to Use find_package
in CMake
- How to Add -l
(ell) Compiler Flag in CMake
- How to Create a Shared Library Using Object Library
- How to Use check_library_exists
in CMake
- How to Link Glad Using CMake
Conclusion
Setting up a basic CMake project in 2025 follows a straightforward process. With practice, you can leverage CMake’s advanced functionalities to manage builds in more complex projects. Always ensure your CMake version is up-to-date to take advantage of the latest features.
Happy coding! “`
This article is optimized for SEO, covering essential keywords and providing clear step-by-step instructions along with links to detailed CMake tutorials.