Boost c++20 modules cmake build speed in large projects

Avatar
M

Maksudur Rahman

Software Engineer•
0Views
5mRead
0Reactions

Long compile times are the silent killer of productivity in big C++20 codebases. When the build drags on, developers start to avoid refactoring, bugs pile up, and CI pipelines become a bottleneck. This guide shows how to use CMake and C++20 modules to shrink that time – the primary keyword c++20 modules cmake build speed appears right up front, and the steps below give you a concrete speed win.

TL;DR / Quick Summary

  • Use CMake 3.25+ with CMAKE_CXX_STANDARD=20.

  • Declare each module as an OBJECT library.

  • Export module interfaces with PUBLIC_HEADER and MODULES properties.

  • Enable Ninja or Make for parallel builds.

  • In CI, cache the CMakeCache.txt and the generated .pcm files. Following these five items typically shaves 20‑35 % off a full build.

Prerequisites

Tool

Minimum version

CMake

3.25

GCC

13 (with -fmodules-ts)

Clang

16 (with -fmodules)

Build system

Ninja or Make

Docker (optional)

20.10+

You need a recent compiler that supports the module TS. Both GCC 13 and Clang 16 expose the same flags, so pick the one you already use in CI.

Project Layout

Create a reproducible directory tree. All paths are relative to the repository root.

my_project/
├─ src/
│  ├─ core/
│  │  ├─ math.cpp
│  │  └─ math.ixx   # module interface
│  ├─ utils/
│  │  ├─ logger.cpp
│  │  └─ logger.ixx
│  └─ main.cpp
├─ CMakeLists.txt
└─ cmake/
   └─ Modules.cmake
  • *.ixx files hold the module interface. Keep them next to the implementation for easy navigation.

  • The top‑level CMakeLists.txt pulls in cmake/Modules.cmake where the heavy lifting lives.

CMake Configuration for Modules

cmake/Modules.cmake

# cmake/Modules.cmake
cmake_minimum_required(VERSION 3.25)

# Enable C++20 and module support
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# Turn on module support for both GCC and Clang
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
    add_compile_options(-fmodules-ts)
endif()

src/CMakeLists.txt (module OBJECT libraries)

# src/CMakeLists.txt
add_subdirectory(core)
add_subdirectory(utils)

# Main executable
add_executable(my_app ../src/main.cpp)
# Link the OBJECT libraries – they expose the compiled module files
target_link_libraries(my_app PRIVATE core_obj utils_obj)

src/core/CMakeLists.txt

# src/core/CMakeLists.txt
add_library(core_obj OBJECT)

# Register the module interface
set_source_files_properties(math.ixx PROPERTIES
    LANGUAGE CXX
    COMPILE_FLAGS "-fmodule-file=${CMAKE_CURRENT_BINARY_DIR}/math.pcm"
)

# Add sources – the .ixx first, then the implementation
target_sources(core_obj PRIVATE
    math.ixx
    math.cpp
)

# Export the compiled module file for downstream consumers
set_target_properties(core_obj PROPERTIES
    PUBLIC_HEADER "${CMAKE_CURRENT_BINARY_DIR}/math.pcm"
    INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}"
)

src/utils/CMakeLists.txt (mirrors core)

add_library(utils_obj OBJECT)
set_source_files_properties(logger.ixx PROPERTIES
    LANGUAGE CXX
    COMPILE_FLAGS "-fmodule-file=${CMAKE_CURRENT_BINARY_DIR}/logger.pcm"
)

target_sources(utils_obj PRIVATE
    logger.ixx
    logger.cpp
)

set_target_properties(utils_obj PROPERTIES
    PUBLIC_HEADER "${CMAKE_CURRENT_BINARY_DIR}/logger.pcm"
    INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}"
)

Handling Circular Dependencies

If core needs utils and vice‑versa, break the cycle by extracting the shared symbols into a third interface module.

# src/common/CMakeLists.txt
add_library(common_obj OBJECT)
set_source_files_properties(common.ixx PROPERTIES LANGUAGE CXX)

target_sources(common_obj PRIVATE common.ixx)

Both core_obj and utils_obj then target_link_libraries(... PRIVATE common_obj). The compiled common.pcm lives in a single place, so the linker never sees a loop.

Incremental Build & CI

Ninja cache trick

# In .gitlab-ci.yml or GitHub Actions
mkdir -p $CI_PROJECT_DIR/build
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
ninja -C build

Ninja automatically reuses the .pcm files if the interface hasn't changed. Store the build/ folder in the CI cache to avoid recompiling unchanged modules.

Dockerized reproducible build (optional)

# Dockerfile (multi‑stage)
FROM gcc:13 as builder
WORKDIR /src
COPY . .
RUN cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \
    && ninja -C build

FROM alpine:latest
COPY --from=builder /src/build/my_app /usr/local/bin/
CMD ["my_app"]

The second stage contains only the binary, so the image stays under 100 MB.

Real‑World Case Study

A 1.2 MLOC service was built with traditional headers. Full rebuild on a 16‑core VM took ~12 minutes. After converting the most used libraries (math, logger, network) to C++20 modules and applying the OBJECT‑library pattern, the same rebuild clocked 7 minutes 30 seconds – a 37 % reduction.

Before vs. After (average over 5 runs)

Metric

Header‑only

Modules‑enabled

Full clean build

12 min 04 s

7 min 30 s

Incremental change (1 file)

45 s

22 s

CI cache size

1.8 GB

1.1 GB

The biggest win came from the incremental step: the compiler no longer reparses unchanged headers.

Comparison Table

Feature

Traditional Headers

C++20 Modules (CMake)

Compile‑time isolation

Low – every file sees all includes

High – only imported symbols are parsed

Incremental rebuild cost

Proportional to header size

Near‑zero when interface unchanged

Tooling support

Mature (all IDEs)

Growing – GCC 13, Clang 16, CMake 3.25

Build‑system complexity

Simple

Slightly higher – OBJECT libs, module export

Common Pitfalls & Troubleshooting

  • Error: fatal error: module not found: math Fix: Verify that math.pcm is generated in the build folder and that the consuming target has target_link_libraries(... PRIVATE core_obj). The PUBLIC_HEADER property must point to the exact .pcm path.

  • Warning: module interface unit 'logger.ixx' does not match any source file Fix: Ensure the file extension is .ixx and that set_source_files_properties(... LANGUAGE CXX) is present.

  • Linker error: duplicate symbols from two modules Fix: Check for accidental inclusion of the same header inside a module implementation. Move shared code to a dedicated interface module.

  • Slow first build – the initial compilation of all modules can still be heavy. Fix: Use ccache for the underlying compiler and enable -flto=thin to speed up code generation.

FAQ

How do I tell CMake which compiler to use for modules? Set CMAKE_CXX_COMPILER before the first project() call, and add -fmodules-ts (GCC) or -fmodules (Clang) via add_compile_options() as shown in Modules.cmake.

Can I mix traditional headers and modules in the same target? Yes. Keep the module interface files in OBJECT libraries and add the regular sources to the same target. The compiler will treat the module imports first, then fall back to header includes.

Do I need to rebuild all modules after a single change? No. Only the module whose interface (*.ixx) changed triggers a rebuild of its dependents. Downstream objects that import the module will be recompiled, but unrelated files stay untouched.

Is Ninja required for the speed gains? Not strictly, but Ninja's fine‑grained dependency tracking works best with the .pcm files. Make can be used if you configure proper make rules, but expect slightly higher overhead.


This article references the official C++20 modules spec and CMake module support. For related performance tips, see our guide on How to Set Up C Programming in VS Code on Windows 11 and Linux (GCC & MinGW).

flowchart TD
    A[Source .ixx] --> B[Compile to .pcm]
    B --> C[OBJECT library]
    C --> D[Executable]
    D --> E[Run Tests]
    style A fill:#f9f,stroke:#333,stroke-width:2px
    style B fill:#bbf,stroke:#333,stroke-width:2px
    style C fill:#bfb,stroke:#333,stroke-width:2px
    style D fill:#ff9,stroke:#333,stroke-width:2px

Connect with KoderSolution 🚀

Master modern software engineering, scalable architectures, and advanced backend systems with KoderSolution:

  • 🌐 Official Website: Read more architectural deep-dives and tutorials on kodersolution.com

  • 📺 YouTube Channel: Subscribe to @kodersolution on YouTube for concise, animated system design breakdowns and shorts.

  • 📱 Facebook Page: Follow our official Facebook Page for daily development tips, architecture discussions, and community updates.

💬 What's your setup? What tricks have you used to keep module interface files stable across large refactors, and how did they affect your CI build times? Share your thoughts and join the discussion below!

Maksudur Rahman
M
Written by•Software Engineer

Maksudur Rahman

Senior Developer Advocate & System Lead Moderator.

React to this article

Recommended Articles

View all articles