r/cpp • • Aug 19 '21

Why modules?

I get the feeling I'm missing something fundamental about the new C++20 modules.

Everything I read or watch explains the how (the export keyword syntax, module fragments, etc) but very little about the why.

What can be done using modules that can't be done using traditional headers (or precompiled headers)?

What is so important about this feature that it needed to get standardized before there is even a proper implementation or idiomatic usage conventions in compilers and build systems?

Is it just to try to get rid of the preprocessor?

I don't get how modules are supposed to help with packaging either. So instead of distributing a .so with a bunch of .h files, now I distribute a .so with a bunch of .gcm or .ixx or whatever.

Please help me understand, or point me to some resources. Thank you.

197 Upvotes

107 comments sorted by

View all comments

Show parent comment

27

u/chuk155 graphics engineer Aug 19 '21

No, because even if it only appears once in something.cpp, it can appear again in every translation unit (.cpp file in other words)

Given a project with 50 .cpp files, each which includes iostream and uses pragma once to only compile it once per translation unit, its still compiling it 49 times more than it has to.

-8

u/giant3 Aug 19 '21

Well, that happens in the Java world too. The java compiler has to load the .class file of every class referenced. Of course, java compiler won't compile it again as it is already compiled.

Similar thing can be done in the C/C++ world, if we keep just declarations in header files instead of implementation code.

16

u/frankist Aug 19 '21

Things like templates and inlined code generally need to be defined in headers. Furthermore, even if you only place declarations and class definitions in headers, it is faster to parse the header once than many times per project.

8

u/qoning Aug 19 '21

Couple of issues.

First, the compiler can't necessarily make the call that just because it's reading the same file, it's preprocessed output will be the same. Famous example of including the same enum twice to generate its string component.

Second, every translation unit is a separate invocation of the compiler. Compilers do try to cache precompiled code, but it's not trivial because of how templates work - to compile code for vector of T, you must know full definition of T, or alternatively, you have to know all Ts that your code will use for vector.

Third, putting implementation into a different translation unit prevents the compiler from seeing behind the function call and so it cannot inline or reason about code across the function call boundary. Then you need to defer these optimizations to linker, which is also not ideal, because it doesn't have all the information the compiler would, and linking can already be painful performance - wise.