Header units in C++20 are a bridge between traditional header files and modern modules. They allow you to import existing header files as if they were modules, facilitating the integration of legacy code with new module-based code.
To create a header unit, you use the import
statement with the header file enclosed in quotes. This tells the compiler to treat the header file as a module-like entity. Here’s an example:
// Player.h
#pragma once
#include <iostream>
#include <string>
class Player {
public:
Player(const std::string &name) : name{name} {}
void sayHello() const {
std::cout << "Hello, my name is " << name;
}
private:
std::string name;
};
// main.cpp
import "Player.h";
int main() {
Player player{"John"};
player.sayHello();
}
Hello, my name is John
import
instead of #include
can simplify the dependency graph of your project, making it easier to manage and understand.#include
directives can sometimes lead to inconsistencies and require careful management.Suppose you have a legacy project that heavily relies on traditional headers. You can start by converting some of these headers into header units:
// Utilities.h
#pragma once
#include <iostream>
#include <string>
void printMessage(const std::string &message) {
std::cout << message << "\n";
}
// main.cpp
import "Utilities.h";
int main() {
printMessage("Hello from header unit!");
}
Hello from header unit!
Header units in C++20 provide a way to import traditional header files as modules, enabling smoother integration of legacy code with new module-based projects.
They offer improved compile times and a cleaner syntax, although they come with some limitations in terms of compiler support and mixed usage.
Answers to questions are automatically generated and may not have been reviewed.
A detailed overview of C++20 modules - the modern alternative to #include
directives. We cover import
and export
statements, partitions, submodules, how to integrate modules with legacy code, and more.