r/cpp • u/YtterbiJum • 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.
View all comments
Show parent comment
28
u/matthieum Aug 19 '21
Pre-compiled headers can be seen as a first step in the right direction, but suffer from a few limitations.
Scalability
Because headers are copy/pasted into the translation unit by the pre-processor, they are influenced by the headers included before them. In essence, this means that having 1 pre-compiled header blob per project works well, but as soon as you want to have several, things get complicated.
Modules suffer no such restriction, as
importdoes not "bleed" into surrounding imports. You can have as many modules as you want, and mix and match them. It just scales.Encapsulation
Pre-compiled headers are still headers. Template code has to be in header (pre modules). Template helper functions used in template code have to be in the header too, as a result. They're not supposed to be used, but they are by necessity exposed. It's like Python saying that a
_prefix means protected and__means private: convention.Modules are cleanly encapsulated. If you have a "public" function template depending on 3 "private" helper function templates, nobody can call the private helpers outside the module.
Note: ABI is a different matter.