In C++20, a module can be separated into an interface file and an implementation file. This separation helps organize code and manage dependencies more effectively.
The module interface file defines the public-facing API of the module. It includes the declarations of functions, classes, variables, and any other entities that are intended to be accessible by other parts of the program.
The interface file uses the export
keyword to make these declarations available outside the module. Here’s an example:
// Player.cppm
export module Player;
import <string>;
export class Player {
public:
Player(std::string Name);
void SayHello();
std::string GetName();
private:
std::string Name;
};
The module implementation file contains the actual definitions of the functions and other entities declared in the interface file.
It uses the module
keyword without export
, indicating that it provides the internal details of the module. Here’s an example:
// Player.cpp
module Player;
import <iostream>;
Player::Player(std::string Name) : Name{Name} {}
void Player::SayHello() {
std::cout << "Hello there! I am " << Name;
}
std::string Player::GetName() {
return Name;
}
Visibility:
Keywords:
export
to make declarations public.module
without export
.Purpose:
Here’s how you might use these files in a project:
// main.cpp
import Player;
#include <iostream>
int main() {
Player player("John");
player.SayHello();
std::cout << "Player's name: "
<< player.GetName();
}
A module interface file in C++20 defines the public API using export
, while an implementation file contains the actual definitions using module
.
This separation enhances encapsulation, maintainability, and can improve compile times.
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.