Post

02. CMake Tutorial, Multi-File C++

02. CMake Tutorial, Multi-File C++

CMake


Prerequisites


1. How to use CMake with Multi-File?

In this tutorial, we extend the basic example to a more realistic project structure:

  • 2 header files (.h)
  • 2 source files (.cpp)
  • 1 main.cpp

We will learn how to organize and build a multi-file C++ project using CMake.

2. Tutorial

2-1. Project Structure

1
2
3
4
5
6
7
8
9
project/
 ├── CMakeLists.txt
 ├── include/
 │    ├── math_utils.h
 │    └── print_utils.h
 └── src/
      ├── main.cpp
      ├── math_utils.cpp
      └── print_utils.cpp

2-2. Context

Header

include/math_utils.h
1
2
3
4
#pragma once

int add(int a, int b);
int multiply(int a, int b);
include/print_utils.h
1
2
3
#pragma once

void print_result(const char* label, int value);

Source Files

src/math_utils.cpp
1
2
3
4
5
6
7
8
9
10
11
#include "math_utils.h"

int add(int a, int b) 
{
    return a + b;
}

int multiply(int a, int b) 
{
    return a * b;
}
src/print_utils.cpp
1
2
3
4
5
6
7
#include <iostream>
#include "print_utils.h"

void print_result(const char* label, int value) 
{
    std::cout << label << ": " << value << std::endl;
}

Main

src/main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include "math_utils.h"
#include "print_utils.h"

int main() 
{
    int sum = add(3, 4);
    int product = multiply(3, 4);

    print_result("Sum", sum);
    print_result("Product", product);

    return 0;
}

CMakeLists

1
2
3
4
5
6
7
8
9
10
11
12
cmake_minimum_required(VERSION 3.10) 
project(MyApp) 

# Specify include directory 
include_directories(include) 

# Define executable and source files 
add_executable(MyApp 
	src/main.cpp 
	src/math_utils.cpp
	src/print_utils.cpp 
)

2-3. Context Detail

1. include_directories(include)
  • Adds include/ folder to the compiler’s header search path
2. add_executable(...)
1
2
3
4
5
add_executable(MyApp
    src/main.cpp
    src/math_utils.cpp
    src/print_utils.cpp
)
  • Compile all .cpp files
  • Link them together
  • Produce executable MyApp

2-4. Build Process

1
2
3
4
5
mkdir build
cd build
cmake ..
cmake --build .
Debug\MyApp.exe

3. Compilation Model

Each .cpp file is compiled separately:

1
2
3
math_utils.cpp → math_utils.o
print_utils.cpp → print_utils.o
main.cpp → main.o

Then linked:

1
math_utils.o + print_utils.o + main.o → MyApp
This post is licensed under CC BY 4.0 by the author.