Will modules in c++20 reduce compile time compared to traditional header-files?
Yes, one of the advantages of modules is that it can reduce compilation times. For comparison, here's how it's done today:
// foo.hpp
// some code
// a.cpp
#include "foo.hpp"
// b.cpp
#include "foo.hpp"
Now when the 2 translation units a.cpp
and b.cpp
are compiled, some code
is textually included into these source files, and hence some code
is compiled twice. While the linker will take care that only one definition is actually in the final executable, the compiler still has to compile some code
twice, which is wasted effort.
With modules, we would have something like:
// foo.hpp
export module foo;
// some code
// a.cpp
import foo;
// b.cpp
import foo;
Now the compilation process is different; there is an intermediate stage where foo.hpp
is compiled into a format that is consumable by a.cpp
, and b.cpp
, which means that the implementation files do not need to compile some code
, they can just use the definitions in some code
directly.
This means that the foo.hpp
only needs to be compiled once, which can lead to potentially large reductions in compile times, especially as the number of implementation files that consume the module interface unit increases.
"The mechanism for accessing headers from implementation files is to use the include directive from the C preprocessor. In other words, your headers are implicitly copied many times.
There are many copies of all header files scattered across a project, and the compiler has to pass through and parse them over and over again. One of the most visible problems is code compilation times.
Modules effectively replace header files and the preprocessor include directive. The solution proposed by modules suggests that we get rid of textual inclusion with the C preprocessor and, therefore, all of its drawbacks." [Each module handled just once. See Table 2]
Reference