All Recipes
Home/Modules/Module Basics
📦beginner

Module Basics

Create and use C++20 modules

Example Code

cpp
// math.cppm - Module interface file
export module math;
export int add(int a, int b) {
return a + b;
}
export int multiply(int a, int b) {
return a * b;
}
// Internal helper - not exported
int internal_helper() {
return 0;
}
// main.cpp - Using the module
import math;
#include <iostream>
int main() {
std::cout << add(5, 3) << std::endl; // 8
std::cout << multiply(4, 7) << std::endl; // 28
// internal_helper(); // Error: not exported
return 0;
}
/* Compilation (example with g++):
g++ -std=c++20 -fmodules-ts -c math.cppm
g++ -std=c++20 -fmodules-ts main.cpp math.o -o main
*/

Explanation

Modules provide a modern alternative to header files. They offer better compile times, explicit control over exported symbols, and no need for include guards. Use 'export module' to declare a module and 'export' for public symbols.

Key Points

  • 1'export module name;' declares module
  • 2'export' makes symbols public
  • 3'import name;' uses module
  • 4Faster compilation than headers