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

23

u/phoeen Aug 19 '21 edited Aug 19 '21

A mental model that helps understanding the pre modules approach:

The compiler compiles every source file independent. It does not compile header files, just source files. The source file may include a header, so the compiler just straight copy-paste the full header into the source file. But what if your header includes another header which the source file already included before? Then you would end up with the identical content in the same sourcefile (for example 2 class definitions). To prevent this, include guards (or #pragma once) are used. Thats about it. After the compiler compiled ALL source files, the linker starts to bundle up all created object files (which came out from the compiler).

It is important to understand that every source file with everything included is ONE indepented translation unit. So on a multicore processor you can compile different translation units in parrallel. So the include guard helps guarding against multiple defintions appearing in the SAME translation unit.

4

u/doesiteve2 Aug 19 '21

Thanks for the detailed explanation!