π οΈ CMake Tutorial: Build C++ Projects Easily
What is CMake?
CMake is an open-source, cross-platform build system generator. It helps you manage the build process of your C++ (and other language) projects, generating native build files for systems like Make, Ninja, or Visual Studio.
Why Use CMake?
- Portability: Works on Linux, Windows, macOS.
- Scalability: Handles small and large projects.
- Flexibility: Supports many compilers and IDEs.
- Modern Features: Supports out-of-source builds, testing, packaging, and more.
1. Basic Project Structure
my_project/
βββ CMakeLists.txt
βββ main.cpp
2. Writing a Simple CMakeLists.txt
main.cpp
#include <iostream>
int main() {
std::cout << "Hello, CMake!" << std::endl;
return 0;
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(HelloCMake)
add_executable(hello_cmake main.cpp)
cmake_minimum_required: Specifies the minimum CMake version.project: Names your project.add_executable: Defines an executable target.
3. Building and Running
From your project root:
$ mkdir build
$ cd build
$ cmake ..
$ make
- The binary will be in the
build/directory (e.g.,build/hello_cmake).
Run it:
$ ./hello_cmake
4. Adding a Library
Suppose you have a helper library:
helper.h
#pragma once
int add(int a, int b);
helper.cpp
#include "helper.h"
int add(int a, int b) { return a + b; }
Update your CMakeLists.txt:
cmake_minimum_required(VERSION 3.10)
project(HelloCMake)
add_library(helper helper.cpp)
add_executable(hello_cmake main.cpp)
target_link_libraries(hello_cmake PRIVATE helper)
5. Useful CMake Tips
- Use
target_include_directoriesto add include paths. - Use
set(CMAKE_CXX_STANDARD 17)to set the C++ standard. - Out-of-source builds keep your source directory clean.
- Use
cmake --build .for a portable build command.
6. Further Resources
Summary
CMake is a powerful tool for managing C++ builds. With simple configuration files and support for all major platforms, itβs a must-learn for modern C++ development!