Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Modules and interface boundaries in C++

A named module groups translation units and exposes declarations through export. import lets clients use its interface without textually including a file. The module boundary separates API from implementation, but is neither a security boundary nor a separate namespace.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

export module M;
export int answer();

// Separate implementation unit:
module M;
int answer() { return 42; }

// Separate importing translation unit:
import M;

A named module is a collection of translation units sharing a module name. Exactly one is the primary interface unit, which has the module declaration export module M;. A global module fragment introduced by module; may precede that declaration. A non-partition implementation unit is declared with module M;, whereas an implementation partition is declared with module M:Part;. export exposes declarations to clients, and import M; enables lookup of exported names. A module does not itself create a namespace.

The interface boundary controls name availability, not code secrecy. Unexported names do not become an ordinary client API merely through an import, but declarations needed to interpret exported entities can still be reachable to the compiler. In the example, the client calls get_answer(), while helper() stays in the implementation unit's unnamed namespace.

Partitions, such as M:Part, divide a module into units that can be imported only within the same module using import :Part;. Interface partitions must be directly or indirectly re-exported by the primary interface. export import N; re-exports a dependency. Importing a named module does not expose macros; import "header.h"; denotes a distinct header unit, which can expose macros.

The example consists of three separate files, not one source file. Build the interface before dependent units and link all object files. Module build options must be selected for the compiler; a C++23 flag alone does not attest production operation. The supplied source is an evolving working draft, not a frozen C++23 publication.

Examples

// answer.cppm
export module answer;
export int get_answer();

// answer_impl.cpp
module answer;
namespace {
    int helper() { return 42; }
}
int get_answer() { return helper(); }

// main.cpp
import answer;

int main() {
    return get_answer() == 42 ? 0 : 1;
}

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources