226 points · by ingve · 1y ago · 261 comments
1. all the .h files were compiled, and emitted as a binary that could be rolled in all at once
2. each .h file created its own precompiled header. Sounds like modules, right?
Anyhow, I learned a lot, mostly that without semantic improvements to C++, while it made compilation much faster, it was too sensitive to breakage.
This experience was rolled into the design of D modules, which work like a champ. They were everything I wanted modules to be. In particular,
The semantic meaning of the module is completely independent of wherever it is imported from.
Anyhow, C++ is welcome to adopt the D design of modules. C++ would get modules that have 25 years of use, and are very satisfying.
Yes, I do understand that the C preprocessor macros are a problem. My recommendation is, find language solutions to replace the preprocessor. C++ is most of the way there, just finish the job and relegate the preprocessor to the dustbin.
Yup, I think this is the core of the problem with C++. The standards committee has drawn a bad line that makes encoding the modules basically impossible. Other languages with good module systems and fast incremental builds don't allow for preprocessor style craziness without some pretty strict boundaries. Even languages that have gotten it somewhat wrong (such as rust with it's proc macros) have bound where and how that sort of metaprogramming can take place.
Even if the preprocessor isn't dustbined, it should be excluded from the module system. Metaprogramming should be a feature of the language with clear interfaces and interactions. For example, in Java the annotation processor is ultimately what triggers code generation capabilities. No annotation, no metaprogramming. It's not perfect, but it's a lot better than the C/C++'s free for all macro system.
Or the other option is the go route. Don't make the compiler generate code, instead have the build system be responsible for code generation (calling code generators). That would be miles better as it'd allow devs to opt in to that slowdown when they need it.
The truth is 98% of the preprocessor is fine - it's ifdefs for platforms and defines of constants and inline functions that are defined exactly once and never redefined. Because modules supports none of this, that means we can't modulize Windows.h. Or zlib. Or gtest.
The committee should have remembered that one of the selling points of C++ is C compatibility, and figured out a way to get modules to work with 98% or the preprocessor and forbid only the nasty 2%.
Importantly, no they did not.
They put a boundary on the preprocessor containing preprocessing within the module definition and not the code importing the module.
And that's where a lot of the loss and compatibility problems have come into play. That's why you can't, for example, share a module between builds. Because the ifdefs that built the module in the first place may have changed from one build to the next.
It was good that the committee bound the preprocessor, but they simply didn't go far enough.
C++ is making strides to adding the language features needed to dustbin modules. A lot of the work of consteval can replace a lot of what the preprocessor is doing.
> Because modules supports none of this, that means we can't modulize Windows.h. Or zlib. Or gtest.
And see, that's the issue. Modules do actually support all this. We can in fact modularize windows.h, zlib, or gtest. The issue is the `windows.module` still has to be rebuilt with every application that imports it because those `ifdefs` could evaluate differently depending on what env variables the build system sets before building. The module can't be just a simple AST built once. Maybe once for a project, but that's about it. And that's the rub. Change anything that causes the module to recompile and you spend exactly the same time you'd spend on precompiled headers.
Yes, this was tedious, but we do it for each of our supported platforms.
But we can't do it for various C libraries. This created a problem for us, as it is indeed tedious for users. We created a repository where people shared their conversions, but it was still inadequate.
The solution was to build a C compiler into the D compiler. Now, you can simply "import" a C .h file. It works surprisingly well. Sure, some things don't work, as C programmers cannot resist put some really crazy stuff in the .h files. The solution to that problem turned out be we discovered that the D compiler was able to create D modules from C code. Then, the user could tweak by hand the nutburger bits.
This is the same solution that Apple chose for Swift <-> Objective C interop. I wonder if someone at Apple was inspired by this decision in D!
Herb Sutter, Andrei Alexandrescu and myself once submitted an official proposal for "static if" for C++, based on the huge success it has had in D. We received a vehement rejection. It demotivated me from submitting further proposals. ("static if" replaces the C preprocessor #if/#ifdef/#ifndef constructions.)
C++ has gone on to adopt many features of D, but usually with modifications that make them less useful.
It seems particularly tricky to define a template in a module and then instantiate it or specialize it somewhere else.
D also has an `alias` feature, where you can do things like:
alias Q = abc.T;
where from then on, `abc.T` can be referred to simply as `Q`. This also eliminates a large chunk of purpose behind the preprocessor.C++ has adapted the ‘using’ keyword now to seem fairly similar to alias, but can’t completely subsume macros unfortunately.
For normal functions or classes, we have forward declarations. Something similar needs to exist for templates.
D does not require names in global scope to be declared lexically before they are used. C++ only does this for class/struct scopes. For example:
int bar() { foo(); }
int foo() { bar(); }
compiles and runs (and runs, and runs, and runs!!!).This seems incredibly wasteful, but of course still marginal better than just #including code which is the alternative.
The next major advance to be completely ignored by standards committees will be the 100% memory safe C/C++ compiler, which is also implemented and works amazingly well: https://github.com/pizlonator/fil-c
Tools like ccache have been around for over two decades, and all you need to do to onboard them is to install the executable and set an environment flag.
What value do you think something like zapcc brings that tools like ccache haven't been providing already?
It avoid instantiating the same templates over and over in every translation unit, instead caching the first instantiation of each. ccache doesn't do this: it only caches complete object files, but does not avoid repeated instantiation costs in each object file.
I'm afraid this feature is at best a very minor improvement that hardly justifies migrating a whole compiler. To be blunt, it's not even addressing a problem that exists or makes sense to even think about. I will explain to you why.
I've been using ccache for years and I never had any problem getting ccache to support template code. Why? Because the concept of templates is ortogonal to compiler caches. It matters nothing, if you understand how compiler caches work. Think about it. You have the source file you are compiling, you have the set of build flags passed to the compiler, and you have the resulting binary.
That's the whole input, and output.
It's irrelevant if the code features templates or not.
Have you checked if the likes of zapcc is fixing a problem that actually doesn't exist?
You used many words just so say "ccache is a build cache".
> it still needs to rebuild the whole translation unit from scratch if a single line in some header changes.
You are using many words to say "ccache rebuilds a translation unit when it changes".
What point were you trying to make?
EDIT: Oh, found the tradeoff:
hollerith on Feb 21, 2024 | prev | next [–]
>Fil-C is currently about 200x slower than legacy C according to my tests
But also consider that it's one guy's side project! If it was standardized and widely adopted I'm certain the performance penalty could be reduced with more effort on the implementation. And I'm also sure that for new C/C++ code that's aware of the performance characteristics of Fil-C that we could come up with ways to mitigate performance issues.
For the high-end performance-engineered cases that C++ is famously used for, the performance loss may be understated since it actively interferes with standard performance-engineer techniques.
It may have a role in boring utilities and such but those are legacy roles for C++. That might be a good use case! Most new C++ code is used in applications where something like Fil-C would be an unacceptable tradeoff.
> It's not even possible to link to unsafe code.
This makes it rather theoretical.
It wraps all of the typical API surface used by Linux code.
I’m told it has found real bugs in well-known packages as well, as it will trap on unsafe but otherwise benign accesses (like reading past one the end of a stack buffer).
Of course it was completely ignored. Did you expect the standards committee to enforce caching in compilers? That's just not its job.
> The next major advance to be completely ignored by standards committees will be the 100% memory safe C/C++ compiler, which is also implemented and works amazingly well: https://github.com/pizlonator/fil-c
Again—do you expect the standards committee to enforce usage of this compiler or what? The standards commitee doesn't "standardize" compilers...
Of course, these tools are of interest to the broader C++ community. Thanks for sharing.
I think there is a hefty deal of ignorance in your comment. A standardization process is not pull-based, it's push-based.
If you feel you have a nice idea that has technical legs to stand, you write your idea down and put together a proposal and then get in touch with committee members to present it.
The process is pretty open.
> Certainly more useful than anything else the standards committees have done in the past 10 years.
Do you understand the "standards committee" is comprised of people like you and me, except they got off their rear-end and actually contribute to it? You make it sound like they are a robe-wearing secret society that is secluded from the world.
Seriously, spend a few minutes getting acquainted with the process, what it takes to become a member, and what you need to do to propose something.
There are also quite a few compiler cache systems around.
For example, anyone can onboard tools like ccache by installing it and setting an environment variable.
I'm sure you must be aware, these compiler tools do not constitute a language innovation. I'd also imagine that both are not productions ready in any sense, and would be very difficult to debug if they were not working correctly.
C++ build times are actually dominated by redundant parsing of headers included in multiple .cpp files. And also redundant template instantiations in different files. This redundancy still exists when using ccache.
By caching the individual language constructs, you eliminate the redundancy entirely.
ccache doesn't add anything over make for a single project build.
Would have been dirt simple to migrate existing codebases over to using it (find and replace include with import, mostly), and initial implementations of it on the compiler side could have been nearly identical to what's already there, while offering some easy space for optimizing it significantly.
Instead they wanted to make an entirely new thing that's impossible to retrofit into existing projects so its basically DOA
The committee has taken backwards compatibility, backwards - refusing to introduce any nuance change in favor of a completely new modus operandi. Which never jives with existing ways of doing things because no one wants to fix that 20 year old codebase.
We want new stuff, but in order to do that we must break old stuff. Like breaking old habits, except this one will never die.
As in `#include <vector>` also performs `#include <iterator>` but `import vector` would only import vector, requiring you to `import iterator`, if you wanted to assign `vec.begin()` to a variable?
Or is it more like it shouldn't matter in which order you do an import and that preprocessor directives in an importing file shouldn't affect the imported file?
#define private public
#import <iostream> // muahaha
Or any such nonsense. Nothing I define with the preprocessor before importing something should effect how that something is interpreted, which means not just #define’s, but import ordering too. (Importing a before b should be the same as importing b before a.) Probably tons of other minutiae, but “not leaking context into the import” is a pretty succinct way of putting it.you define #import as "include but no context leaks into it" and that should on its own be enough to let the compiler just, compile that file once and reuse it wherever else its imported. That's like 95% of the benefit of what modules offered but much much simpler
Explicit sub-unit encapsulation. True isolation. No more weird forward declarations, endlessly nested ifdef guards, or insane header dependency graphs. Things just exist as they are separate, atomic, deterministic and reliable.
Modules probably need a revision, and yes, adoption has been slow, but once you start using modules you will never go back. The clarity of explicitly declared interfaces and the freedom from header hell fundamentally changes how you think about organizing C++ code.
Start a new project with modules if you don’t believe me. Try them. That is the largest barrier right now - downstream use. They are not supported because they are not used and they are not used because they are not well supported. But once you use them you will start to eagerly await every new compiler release in hopes of them receiving the attention they deserve.
It's unlikely at this point modules in their current form will ever be anything but a legacy feature in C++. Maybe someday a new implementation will arise, just like noexcept replaced the failed "throws" declaration.
> No more weird forward declarations
We c++ devs just have collectively accepted that this hack is still totally ok in the year 2025, just to improve build times.
I made it one of my first projects after joining the Chrome team to fix that gap, which we documented at [1]. (This reminds me of the article's "The only real way to get those done is to have a product owner...".)
You could even stretch the analogy to talk about how standard JS modules compete against the hacked-together solutions of AMD or CommonJS modules, similar to C++ modules competing against precompiled headers.
That said, the C++ modules problem seems worse than the JavaScript one. The technical design seems harder; JS's host/language separation seems cleaner than C++'s spec/compiler split. Perhaps most importantly, organizationally there was a clear place (the WHATWG) where all the browsers were willing to get together to work on a standard for JS module loading. Whereas it doesn't seem like there's as much of a framework for collaboration between C++ compiler writers.
Modules are horrible for build times. If you change an implementation (i.e something that would not normally involve editing a header) the amount of rebuilding that happens is crazy, compared to any C++ project that was set up with a minimal amount of care.
In terms of rebuild performance in defining the interface vs implementation, there is interest in having rustc handle that automatically, see https://rust-lang.github.io/rust-project-goals/2025h2/relink...
Yes. The C++ standard is an abomination that is both over-specified and wildly under-specified.
Modules are simply never going to work en masse. It is a failed idea.
> it is also unknown how you're gonna export and share modules across dependencies you have no indention of 'porting' to modules...
as a first step you can introduce modules only in private interfaces of your lib. This is also absolutely valid usage..
There is no solution to invent modules in such way that everyone just switch compiler flag and have fun. If you expect this, so...
See Zig for a working example of that idea (which also turned out to be a viable cmake replacement for C and C++ projects)
It could even be reduced to compiler vendors agreeing on a convention to compile and run a build.cpp file. Everything else could live in 3rd party code shipped with a project.
good build systems need to bea real programming language. The more declaritive the better - this is different from the project that often should be a different style
See the book "Large Scale C++ Software Design" by John Lakos for more detail in this direction.
Instead, I launched a compilation.
As the article mentions, you need a close relationship between the compiler and build system, which Google already has. The google build tooling team got modules to mostly work but only turned them on in limited situations. But we but the bullet and turned them on everywhere, which has sped up compilation of individual files by more than 5x (I forget the exact number).
The remaining problem is that sometimes we get weird compilation errors and have to disable modules for that compilation unit. It's always around templates, and Eigen has been gnarly to get working.
C++ has no future
Not great!
Maybe I don't know what they mean by this, but the header inclusion way is O(N*M), is it not? Where N is the number of source files and M is the average number of dependencies each has (as expressed as #includes).
If M is approaching N -- meaning everything depends on everything -- you probably have bigger problems than compile times.
That's also setting aside precompiled headers. Those wouldn't be N^2 either, even when the precompiled header needs to be precompiled.
The pre processor and linker, as derided as they are, allow for scaling of software size to extremes not possible with supposedly superior languages’ supposedly superior module systems.
Want to build a >billion line of code OS? You can do that with headers and separate compilation units. Good luck doing that with any other tech
Someone somewhere is trying to vibe code the entirety of the Linux kernel using Copilot.
It's a fact that:
- Super large software tends to be C or C++
- One of the unique features of C and C++ is the way software is organized (headers and separate compilation).
- Attempts to bring other languages' approach to modules to C++ have been a complete disaster.
Hence it's an empirical fact that C and C++ have a superior approach to software scaling, and that approach is headers and separate comp. And a preprocessor with macros.
I'm not convinced the "superior" follows. What I'm missing is a causal link between your first and second points - super large software could have been written in C or C++ for reasons other than the header/implementation split (especially if the super large software wasn't so super large at first and grew into its size instead of being planned for that size from the start), and somewhat conversely programming languages with header/implementation splits don't necessarily have corresponding super large software (e.g., OCaml, at least publicly?).
I didn't think modules and separate compilation units are (completely) mutually exclusive? It's not like modules force you to use a single compilation unit for all your code; it just changes where the compilation unit boundaries/dependencies are (though to be fair I'm not entirely certain how much heavy lifting that "just" is doing)
> Want to build a >billion line of code OS? You can do that with headers and separate compilation units. Good luck doing that with any other tech
It's not immediately obvious to me why this must be the case. That's the fundamental limitation of modules systems that supposedly prevents this scaling?
Not the person you're replying to but I can see a problem with some dependency chains.
Let's say you have: stdlib <- A.hpp <- B.hpp (small header) <- C.hpp (likewise) <- many .cpp files.
If you only precompile A.hpp (as is commonly done), the many .cpp files can be compiled in parallel once A.hpp is precompiled, and you get a nice speedup.
If on the other hand you need to precompile everything, then all these cpp files must wait on A, then B, then C to be precompiled
Speaking more abstractly even if there isn't an explicit interface/implementation separation perhaps compilers could pick out and make available interface information "ahead of time" to alleviate/possibly eliminate the effect of otherwise problematic dependency chains? For example, in Rust you "just" need to look for signatures to figure out the interface and you have the corresponding keywords to make searching for those easy without having to fully parse the entire file.
There's also the question of whether super large projects must have problematic dependency chains - hypothetically, if a super large project were written in a language with a module system some work would be done to try to structure it to minimize build time/system pain points. I don't think I can confidently say that that is always (im)possible.
C++ code bases are really a lot longer-lived than any other software builds upon them. Hence we cannot drop it.
Starting with C++17, I think committee has been doing the language a disservice and piled even more and more unintended complexity by rushing "improvements" like modules.
I don't write C++ anymore due to my team switching to Rust and C only (for really old stuff and ABI). I am really scared of having to return though. Not because I am spoiled by Rust (I am though), but because catching up with all the silly things they added on top and how they interact with earlier stuff like iterators. C++ is a perfect language for unnecessary pitfalls. Newer standards just exploded this complexity.
Mozilla and Dropbox did it. LLMs are good at translating between languages, and writing unit tests to make sure things still work the same.
Rust just doesn't have close to the same type of adoption/support yet, especially when considering various embedded platforms.
- GCC switched from C to C++
- CUDA switched from C to C++
But I can understand the decision, and at that time , C++ frontend features and libs were a little bit less horrible.
If you think that "the world seems to have moved on to Rust", I would recommend to look at the job listings. For example, devjobs.de: Rust: 61, C++: 1546. That's 1:25. Maybe in other countries there are more Rust jobs?
https://play.rust-lang.org/?version=nightly&mode=debug&editi...
These are all highly non-parallel problems. They don't gain much from being parallel, and because Rust imposes 'restrict' semantics on even single threaded code you end up making it much harder to write code in these domains.
This has been my experience with Rust. Shared mutability is safe on a single thread without 'restrict' on all your pointers, and Rust has limited options to opt into shared mutability (with lots of ergonomic caveats).
Don't get me wrong though, I still think Rust is a great tool. It just has tradeoffs.
The C++ solution would be to start the threads and use an MPSC queue (which, ironically, Rust also has) in order to update the UI.
Rust will eventually stumble upon ergonomics and allow portions of code to be specified as single threaded or embarrassingly parallel, but unfortunately the community evolved horse blinders early on and isn't letting them go any time soon.
You’re forced into function-call or jump-table dispatch, which tends to be slower.
And give Rust one or two more decades and it will be the same messy kitchen sink language as C++. If anything, Rust is speedrunning C++ history (with the notable exception of fixing static memory safety of course).
Internet hype meets actual industry reality :-).
There are things you can add, but the rot still permeates the foundations, and much of the newness goes partially unused because they're just not at home in C++. Use of `std::optional` and `std::variant` is, as far as I know, still limited, even in newer C++ code, because the ergonomics just aren't there.
variant isn't, yet. We'll eventually get some kind of structural pattern matching that will make variant or it's successor more idiomatic.
C++ does have quite a bit of rot, you're right. But that's the price of building technology people actually use.
Carbon doesn't seem to have any fundamentally new ideas, we'll see how well it fares in the wild.
So I'm afraid no by definition C++ can't adopt Rust's ideas because Rust's ideas were originally impossible C++ ideas.
I agree with your point except for the 'never' qualifier. It was certainly true when Rust was born.
C++ has proven the 'never' part wrong multiple times. I think, by 2030, the only thing that C++ would lack that Rust has right now is the unified toolchain/packaging ecosystem because people are not going to settle that debate.
Everything else is well on its way to be implemented, in one of three forms - core language features (eg: concepts), language features that primarily enable writing more powerful libraries so that you do not have to come up with language features for everything (eg: reflection), and finally tooling support from the compiler as a test bed of what the language could guarantee (lifetime checks and annotations in clang).
Of course Rust is innovating pretty well too, I am very interested in seeing what async/coroutines are going to look like in a few years.
But as it stands, I expect that whatever innovations these languages produce will be picked up by C++ in ~5 years.
This is exactly WHY we dont see a rush movement of C++ developers to Rust throwing away everything for Rust. Rust is trying to solve problems that already not exist 99.9999% of time in modern C++ code style and standards.
Also, some day C++ compilers or tooling will get its own Borrow Checker to completely forget about Rust - this will be done just for fun just to stop arguing with rust-fans :)
The number of people I met in Rust conferences that rewriting at least parts of rather big C++ codebases weren't small either.
However, there is still big amount of code that is purely C++. Many of the older code bases still use C++03-style code too. Or they were written in the OOP design pattern golden era that requires huge reactors to adapt functional / modern code. Anything with Qt will not benefit from smart pointers. Even with Qt 6.
Rust cannot solve these problems since the challenges are not purely technical but social too.
No amount of fallible human vigilance will stop you from forgetting the existence of a C++ quirk in the code you're rushing out before heading out for the night. Human oversight does not scale.
Rust solves 1 category of problems in a way that is not without its costs and other consequences. That is it. There are projects where this is very important, there are other projects where its virtually useless and the consequences just get in the way. It is not magic. It doesn't make anything actually 'safe'.
I bet there's easily tens of thousands of times more C++ code than Rust code out there.