This article aims to summarize the current status as regards Modules and the import keyword with modern compilers, in particular accessing the Standard Library without the need for #include <iostream> and similar.
At the time of writing, two of the most popular C++ compilers (Visual Studio 2022 and Clang) offer full support for modules including importing the Standard Library as a module, while GCC g++ offers some support for writing modules, as detailed below:
- MSVC needs to be installed using the Visual Studio Installer from the “Desktop development with C++” workload with the “C++ Modules for v143 build tools (x64/x86 – experimental)” option selected in order to be able to use
import. The option/std:c++latestneeds to be specified to theclcompiler when using Visual Studio or the command line, and manually compiling the Standard Library into an.objfile is a necessary step. More details here; the syntax to use in your code is (as of version 17.5):import std; - Recent versions (12+) of Clang/LLVM support C++ Modules, including replacing the Standard Library headers, when invoked with the options
-std=c++20,-stdlib=libc++and-fmodules. Compiling from source is one way to access this functionality; the build flag LLVM_ENABLE_MODULES is required and the libcxx project needs to be built too. A rolling/testing distribution should provide these, but ensure you have installed the correctlibc++package. A list of issues is described on this page; the syntax to use in your code (the same as for MSVC) is:import std; - The GCC devel/c++-modules branch has now been folded into trunk; the new C++ modules page is here. The main compile option available to use is
-fmodules-ts, however the C++ Standard Library is not available as animportat the time of writing, so only importing third-party (or your own) modules is supported. Use of theimportkeyword with the Standard Library headers is currently a workaround, for exampleimport <iostream>;Note that subsequent compilations of units which import headers in this way will be quicker, as the module data file is cached.
It is clearly going to take a while for C++ modules to become universally adopted, so the code on this site will likely use #include for the foreseeable future. The example code archive for the tutorial on this site includes both a “headers” and “modules” directory so you can choose which to experiment with (the “modules” versions are all able to be built by Clang/LLVM, and almost all by MSVC).