Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which files do C++ modules go and how is it with templates?

Tags:

c++-modules

From what I understand module interfaces and their implementation can be separated into two different files. Similar as with header.h and source.cpp files.

What is the agreed on name of these files and what file suffix? Do we stick with ".h" for the interface?

So for a very simple case: Would it look, similar to the header-declaration, source-implementation, like so?

// Module Interface: file name: mymodule.h ?
export module my.module;
export void Foo();

// Module implementation: file name mymodule.cpp ?
module my.module;
void Foo() {
   // complex code
}

How does it behave if we write templated code? Is it still "header" (i. e. module interface) only, or can we now move it to the implementation file?

like image 667
SamVanDonut Avatar asked Oct 21 '25 04:10

SamVanDonut


1 Answers

File name conventions (for the four different kinds of module units!) are still forming; the various prototype implementations are likely to develop their own that compete (for a time?). Using the same styling as for header files is certainly a bad idea, because then all three of

#include"a.hh"  // header file
import "a.hh";  // header unit
import a;       // named module

would seem reasonable despite their very different meanings.

(Similarly, don’t use .h for C++ headers so as to distinguish them from C headers.) Non-importable module units (those with a simple module a; that are neither partitions nor interface units) might very well stick with .cpp/.cc/etc., since they don’t require any special attention from (typical) build systems.

Your Foo example is reasonable, but note that (with implementations that mean to support this use case) you could define Foo in the interface and later change that definition without risking an ABI break. (Such a change would, however, cause modification-time-based build systems to recompile the clients, with no benefit on those implementations.) If, however, you make Foo inline (which is optional here but would be required were it defined in the “interface” of a header-file-based library), changes to its definition have ABI implications across all typical implementations.

Templates are still subject to the familiar restrictions: their definitions must be imported—available in the module interface (primary or partition) for external use—for clients to create instantiations, with the usual exceptions for explicit specializations and instantiations. Implementation units are expected to be compiled separately and perhaps shipped in binary form, disqualifying them from providing template definitions for the same reasons as for normal source files.

like image 109
Davis Herring Avatar answered Oct 27 '25 07:10

Davis Herring