Post

01. CMake Tutorial

01. CMake Tutorial

CMake


Prerequisites


1. What is CMake?

This tutorial explains how to build a simple C++ program (main.cpp) using CMake, with a clear explanation of every command and option.

The goal is not just to run commands, but to understand what each part actually does.

Flow:

1
2
3
4
5
6
7
8
9
CMakeLists.txt
   ↓
CMake (configure)
   ↓
Build system (Makefile / Ninja / MSBuild)
   ↓
Compiler (g++, clang)
   ↓
Executable

2. Tutorial

2-1. Project Structure

project/ ├── CMakeLists.txt └── main.cpp

2-2. Context

main.cpp ```cpp #include int main() { std::cout << "Hello CMake!" << std::endl;

1
return 0;  } ```

CMakeLists.txt ```cmake cmake_minimum_required(VERSION 3.10) project(MyApp)

add_executable(MyApp main.cpp)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#### <b>2-3. Context Detail</b>


##### 1. `cmake_minimum_required(VERSION 3.10)`

* Specifies the **minimum required version of CMake**
* Ensures compatibility and avoids unexpected behavior

##### 2. `project(MyApp)`

* Defines the **project name**
* Internally sets variables like:

  * `PROJECT_NAME`
  * `PROJECT_SOURCE_DIR`

##### 3. `add_executable(MyApp main.cpp)`

**This is one of the most important commands**

**Meaning:**

* Create an executable file named `MyApp`
* Compile `main.cpp`
* Link everything into a runnable program

**Equivalent concept (low-level):**

```bash
g++ main.cpp -o MyApp

2-4. Build Process

1
Build Directory → Run CMake → Build Project → Run
1. Create Build Directory
1
2
mkdir build
cd build
  • Separates source files and build artifacts
  • Prevents clutter in your project
  • This is called an out-of-source build (industry standard)
2. Run CMake
1
cmake ..
  • cmake → run the CMake configuration process
  • .. → path to the directory containing CMakeLists.txt

What happens internally:

  • Detects compiler (e.g., g++, clang)
  • Generates build files:

    • Makefile (Linux)
    • .sln / .vcxproj (Windows)
3. Build the Project
1
cmake --build .
  • --build → tells CMake to actually compile
  • . → current build directory
4. Run the Program
1
./MyApp

(Windows: MyApp.exe)

Full Command Summary

1
2
3
4
5
mkdir build
cd build
cmake ..
cmake --build .
./MyApp

3. Important CMake Options

3.1 -DCMAKE_BUILD_TYPE=Release

1
cmake -DCMAKE_BUILD_TYPE=Release ..

3.2 -DCMAKE_CXX_COMPILER=g++

1
cmake -DCMAKE_CXX_COMPILER=g++ ..
This post is licensed under CC BY 4.0 by the author.