Skip to content
Quantoros

What are C++20 modules, and what problem do they solve?

C++Level: IntermediateModern C++ Features

What are C++20 modules, and what problem do they solve?

Hints
  • Identify types, object lifetimes and compile-time decisions.
  • Separate language guarantees from a particular compiler's behavior.

Answer

Module Basics

:Source: src/modules/basic

A module consists of a module interface unit (the public API) and optionally module implementation units. The export keyword marks declarations visible to importers. Everything not exported remains internal to the module.

// math.cppm - module interface unit
export module math;  // module declaration

// Exported - visible to importers
export int add(int a, int b) {
  return a + b;
}

export int multiply(int a, int b) {
  return a * b;
}

// Not exported - internal to module
int helper() {
  return 42;
}
// main.cpp
import math;  // import the module

int main() {
  int sum = add(1, 2);       // OK: exported
  int prod = multiply(3, 4); // OK: exported
  // helper();               // Error: not exported
}

Answer section

Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT

Related questions