Module Interface vs Implementation
Can you explain the difference between a module interface file and an implementation file in C++?
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.
Module Interface File
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;
};
Module Implementation File
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;
}
Key Differences
Visibility:
- The interface file defines what is visible outside the module.
- The implementation file contains internal details that are not exposed.
Keywords:
- The interface file uses
export
to make declarations public. - The implementation file uses
module
withoutexport
.
Purpose:
- The interface file is for declarations.
- The implementation file is for definitions.
Benefits of Separation
- Encapsulation: The implementation details are hidden, promoting better encapsulation and reducing the risk of accidental usage of internal details.
- Compile Times: Separating interface and implementation can lead to better compile times, as changes in the implementation file do not require recompiling code that depends on the module.
Example Usage
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();
}
Summary
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.
C++20 Modules
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.