by john_moscow · 6y ago · 0 comments
This works splendidly with Pascal because each .pas file is split into interface and implementation sections. The interface section is a contextless description of what the module exports, that can be easily translated to a bunch of hash tables for functions, types, etc, that will be blazingly fast.
It's a whole different story with C/C++. In order to support preprocessor macros and C++ templates, referencing a module means recursively "including" a bunch of header files (i.e. reparsing them from scratch), meaning O(n^2) complexity where n is the number of modules. You can speed it up with precompiled headers, but you will still need to separately parse each sequence of references (e.g. #include <Module1.h> \n #include <Module2.h> and #include <Module2.h> \n #include <Module1.h> will need to be precompiled separately. C++20 modules do address this, but since C/C++ is all about backwards compatibility, it's still a hot mess in real-world projects.
That said, C# solves this problem near perfectly. Each .cs file can be easily translated to an mergeable and order-independent "public" part (i.e. hierarchical hash table of public types), and that part can be reused when building anything that references this file. It is also interesting how C# designers achieved most of the usability of C++ templates by using constrained generic types that are actually expanded at runtime (JIT IL-to-native translation to be more specific).
> Simple rule: include files should never include include files. If instead they state (in comments or implicitly) what files they need to have included first, the problem of deciding which files to include is pushed to the user (programmer) but in a way that's easy to handle and that, by construction, avoids multiple inclusions. Multiple inclusions are a bane of systems programming. It's not rare to have files included five or more times to compile a single C source file. The Unix /usr/include/sys stuff is terrible this way.
Plan 9 compilation is very fast. It is small but also it restricts recursive #include, no guards (example [2]), each header has corresponding library, headers included in C file only [1]:
#include <u.h>
#include <libc.h>
void
main(void)
{
...
Remember Go language demo compilation time? Same authors.[0] http://www.lysator.liu.se/c/pikestyle.html
[1] https://www.lysator.liu.se/c/plan9c.html
[2] https://github.com/brho/plan9/blob/master/sys/include/bio.h
Multiple inclusions are hardly a problem nowadays, with header guards it means that subsequent inclusions won't actually include anything and the performance impact is fairly negligible the vast majority of the time. C compilers are pretty damn fast these days and in my experience it's the optimization pass that slows things down the most, not parsing includes.
Also in general I tend to take what Rob Pike says with a grain of salt, he's a very smart guy and he definitely says interesting things but he has weird idiosyncracies. He's definitely worth listening to, but I wouldn't follow his advice blindly. See his weird take about how "syntax highlighting is juvenile" for instance.
See here for a relatively recent take on this:
Beyond that I think that very complicated include graphs are usually a sign that there's an architectural problem with the application, forbidding includes within includes treats the symptom, not really the core of the issue.
As a quick example of some code I wrote not long ago: I have a microcontroller communicating with an external chip over a serial link using a custom protocol. I have a "serial.h" file that describes the API to send and receive serial messages, then a "protocol.h" that implements the higher level protocol. protocol.h includes serial.h since it uses it as a lower layer, it's effectively a dependency. I don't really think it's a problem.
So I'm not really sure that it makes a lot of sense to forbid includes within includes as a rule of thumb. I guess if I was to make a rule it would be "include trees are fine, include graphs are bad"? As in, there shouldn't be cycles in the include graph?
If you’re coming into a code base with new eyes there’s less confusion as to where things came from.
Of course if you’re reading code - ctags, and cscope are invaluable. I’ve yet to use this fancy new LSP stuff but it seems popular.
Convenience headers can be ok occasionally but it kind of runs in the face of writing modular software at times.
Syntax highlighting has caught a few mistakes for me in the past but I do think it’s kind of a crutch.
Say you maintain a library (lib1.h) that exports an API that takes in an argument defined in lib2.h.
If you do not include lib2.h in lib1.h, then the users of your API need to include lib2.h before lib1.h in every source file and header. With a larger number of dependencies, this can become unwieldy for users.
In addition, future maintainers of your library may also find it confusing why things break when includes are reordered.
I find this focus on compilation speed curious. At my last workplace a full built took a good share of the day (!) and was typically done overnight. Building during the daytime was discouraged, as it happened on our workstations, slowing down everything else. We found ways to cope, chiefly learning which subsets are autarkic, i.e. finding the least general Makefile which when invoked would catch your recent changes and wouldn't traverse too much of the tree. Not ideal, but workable.
This will become completely unmanageable once your include count surpasses 20-something, which is normal for large projects.
If your whole source code is written in that manner, and written by people who write code in that manner, this advice is easy to follow.
On the other hand there aren't many files in the Plan 9 source tree that are longer than, what, 3,000 lines? 4,000? Attempting to shoehorn that, and many other well-intended nuggets of wisdom from the Unix 'heritage", into your average commercial codebase, with dozens of third-party libraries and whatnot, is unworkable (I know, I tried).
Some programming advice pearls translate well into any project. "Avoid gratuitous comments like "increment i", use comments to explain the reasoning behind functionality, not describe what the source code already adequately describes" can be applied on any source tree, starting at any point. But some of them -- such as this one -- only work if you write and organize your code in a particular way.
FWIW, I think that this bit of advice was useful back when Pike wrote it, in the age of slow, buggy C compilers (although some would argue we're still in that era!) munching code off of network-mounted drives. Nowadays, not so much -- I think it has readability advantages but I doubt the performance gain (if any is left) is worth the extra programmers' effort. I like to follow it when I'm writing small utilities but I don't really fuss about it for larger projects, and I've never been curious to see how fast it is. I believe (but never measured it, so take it with a grain of salt!) that it's one of those things that 30+ years of computer systems evolution (in the biological sense -- "advancement" is probably too strong a word) has made obsolete.
That's advice from February 21, 1989. They've implemented OS and some GUI applications, for example acme text editor [1]. Maybe it is not that hard.
[1] https://github.com/brho/plan9/blob/master/sys/src/cmd/acme/a...
Instead use few big headers, for instance one public-interface header per system/module which only contains declarations (no inline or template code), and at most one private header for each module (or better none at all). Then keep the dependency tree between modules/systems as flat as possible.
This is especially important for large projects.
C already has similar problems that are worse. For any given function used in a program, you have no guarantee that you can locate where that function is implemented in a straightforward way. In the worst cases, you have to resort to using dumb hacks like ctags or a project-wide recursive grep. It makes it hard to read any given program in the Knuthian way—laid up in bed with a printout to study how it works.
(Go has the same problem. When I started seriously looking at Go, I was surprised that it copied C here, given the strong influence from Oberon.)
> include files should never include include files
Cool, there are two possible outtakes to this:
1) Why aren't include files generated automatically from C files then? (If you can't include anything this means they shouldn't have no "code", so they can't call anything, so they can't include anything or reference anything else)
2) Why aren't they a compilation target? (yes I know modern GCC allows you to do that) but why doesn't C specify a binary representation for them.
Looks like you ask "why convention, not restriction?" It solved their problems while maintaining interoperation with UNIX world [1]. If convention is not enough for you, you may define format and tooling.
The first time the compiler reads the include file, it remembers where the corresponding #endif is for each #if. The next time the file is included, the compiler can skip over the whole included file. There is no performance advantage from outsourcing the conditional to every including location.
Putting an ifndef guard at the location where the file located is not workable. It's terrible boilerplate. To the relatively simple '#include <A.h>' another variable that must be synchronized with dependencies gets added. Plus 2-3 lines for the conditional. At each including location.
Another option is "#pragma once"; it's non-standard, but every popular C compiler (even MSVC) understands it, and has the advantage that there's no risk of accidentally using the same include guard for more than one header file.
The only plausible exceptions are in proprietary compilers for microcontroller SDKs.
For instance out of the top of my head I don't remember how #pragma once decides what constitutes the same include file. If you have symbolic links, or absolute and relative paths for instance, how does it work? I'm sure I can find the answer in the compiler's documentation, but with #ifndef I don't even have to, it's obvious what's going to happen.
I would personally argue that old school guards should be preferred because of this and the fact that they're standard, but I don't feel super strongly about it.
Maybe Delphi compiler works the same way.
Here are a few features that prevent Pascal from being my go-to language:
* Having all function variables declared in var clauses at the start, far away from where they are first used. It eventually gets littered by loop indices and other temporary variables.
* "interface" sections that can easily grow (C/C++ header files are also somewhat similarly inconvenient).
But then again, these languages have been around when computers are not as powerful. And perhaps, keeping these rules is the price of not breaking what works.
Still, I doubt language design alone is enough to make compilation fast (i.e. why FPC is not as fast). There must have been a lot of sorcery in the Borland compilers that we will never know. Also they must have taken advantage of only supporting Windows (and only x86?) back then.
The Delphi compiler was really great, but it was meant primarily for GUI business apps and not any other kind of coding. Result: the compiler hardly optimised. Borland didn't advertise new Delphi releases by referencing benchmark scores for example, but rather new productivity features.
Building fast compiler is not sorcery. Look at Java. JavaC starts out interpreted every time you run it, but it can still compile a large amount of source code very fast. Then at runtime HotSpot C1 can produce machine code from bytecode at a staggering speed. The resulting code even has respectable performance, with the slower (but still fast) C2 compiler only kicking in for where it's really needed.
Delphi is indeed a single-pass compiler. It does not use a normal recursive-descent parser, but a hand-coded parser. Other than that, yes - the Delphi language today is still designed to be extremely efficient to parse and it compiles a million lines of code in seconds.
Hadn't it already been solved in Java even better before? It doesn't look right to praise C# for resolving the problem when C# merely took that idea from Java. C# came up with the templates part though.
What C# didn't copy was the idea of turning every source file into a binary file. A library is just a zip archive of those .class binary files. What's the advantage for C# to not have .class files and to pack everything into a 'proprietary' library format? Why haven't they copied the zip-idea, too?
He was not snatched, he left Borland unhappy with its management and Microsoft was the obvious choice as next employer.
snatching wutt? They could have paid more to keep him.
Not a Microsoft fan either, but Borland managers have no right to complain :)
This requires modules and it's a new technique that post-dates Java 8, so not many Java shops use it yet. However Java 9+ comes optimised this way by default, that's what the 'modules' file is in the JDK lib directory. Class files have their strings extracted and placed into a single string table are compressed, and their offsets then placed into a "perfect hash table" that's guaranteed to satisfy lookups in O(1) or O(2) time.
Modula-3 was also pretty slow compiling, but it also compiled interfaces so that it could refer to them. Unfortunately, the underlying objects could change during a compilation because of partial revelation, so parts of the system would have to be recompiled when the builder found those cases. I'm sure Modula-2 could have been faster in that regard, not having the opportunity for a type to be elaborated more in later compilation units.
Not sure I really get your point here. Even if you remove macros and templates, reading headers is actually necessary just for the sake of knowing the size of structures, the offsets of attributes, etc.
How can _any_ language compile a unit passing a struct Foo on the stack without knowing the size of Foo (and thus having to read, say, foo.h)?
Now I agree that if you play with preprocessor to have conditional things in your headers, reparsing will be necessary, but I guess this has been solved by include guards/pragma once a long time ago. 99% of preprocessor usage is project wide configuration, so wrapping the whole headers is fine.
Not saying this is the best solution, but in practice, that shouldn't make much difference.
A subtle distinction that can make quite a difference though is to provide independent forward declarations. A lot of times, your compiler will just need to know the symbols and signatures (e.g. When passing by reference), and providing the full structure definition is overkill and slower. I don't see enough people taking care to that, which is a pity
The idea is not to compile a unit without knowing the size of Foo. It's about making sure you figure out sizeof(Foo) in near constant time.
With C#/Pascal, it means:
* For each referenced module load its symbol table into RAM. If implemented cleverly, this is literally one read() call.
* For each referenced symbol, search each hash table until you find it. Since the hash tables are only built during compilation, you can auto-size them so that an average lookup takes just 1-2 steps.
* Bonus point: for libraries, you can merge the hash tables. So n is now a number of libraries, not number of files.
With C++ you are stuck reparsing megabytes of code at the beginning of each translation unit. It's millions of times slower than reading a couple of pages from disk to RAM.
The preprocessor does not have side effects. That means whenever a header is compiled, you could store a hash of all used defines and their checksum. Whenever that file should be read again, compare the checksum of the used defines to the one stored. If they are the same, you can reuse the precompiled header. If not, create a new version of the precompiled header for a different set of defines.
99.9% of the time, every single header is included with the exact same set of defines.
config.h
#define I_LIKE_FEATURE_X
b.h
#include "config.h"
struct App {
#ifdef I_LIKE_FEATURE_X
FeatureXImplementation *fx;
#endif
}
The preprocessor can change the size of structs (even redeclare them several times, or create new ones with unique names or ...)That might easily be a lot slower than building a huge hash table at the start.
But there is a huge advantage to be had if the effort of building the large hash table can be shared between all files that are simultaneously built.
Those files are not compatible between major versions, so this probably means they are designed to make them as easy to parse as possible, and map closely to internal compiler structures. This means including a unit is way faster than re-parsing the unit's text.
Additional speculation: those DPU files might contain a copy of relevant definition (like names of fields, sizes and offsets). This means if you have "program" which uses "my_unit" which uses "high_level_comms" which uses "Handle" defined in "low_level_comms", then definition of "Handle" could be copied directly into my_unit.DPU. So when you compile "program", and it includes "my_unit", all you need to read is "my_unit.DPU". You do not care about total size of "high_level_comms" and "low_level_comms" files.
Unfortunately, in C/C++, when people '#include <iostream>', they can now use "std::plus", "mbrtowc" and "timer_getoverrun". Which means including high-level modules has to bring tens of thousands of lines in translation units. (Yes, impl pattern, well-designed interfaces, forward declarations can fix this, but few people bother. Stdlib certainly does not)
Import definitions are not included. There's an import symbol for each import that has a pointer to the definition information which is updated when the used unit is loaded. This linking is fast, and uses a combo of three things: hash code, symbol name and symbol version. Hash codes in the Delphi compiler are cached in each symbol, so each symbol linked is a hash probe and a few string compares at most. The symbol version is a hash of its (original) definition. If there's a version mismatch, Delphi knows it needs to recompile the unit.
(I spent about 6 years working on the compiler at Borland / Codegear / Embarcadero.)
by having a runtime that has higher level instructions like "change that field" moved the onus of knowing where the field is onto the runtime. Another answer is that it's the difference between needing to parse text everytime and having some binary intermediary description (which both delphi and c# have, compare .obj to .dcu and an assembly). This means there is less work to do when a dependency changes in incremental compilation.
This is an implementation detail to me. Most C++ compilers _do_ compile headers if you tell them to.
> by having a runtime that has higher level instructions like "change that field" moved the onus of knowing where the field is onto the runtime
Alright but that's not the same language anymore. With such a runtime you don't compile natively anymore, you compile for a VM that will dynamically allocate stack space and translate adresses.
C and C++ compilers will pre-compile one header if you ask nicely, the first one you include. Compiling multiple independent headers is very hard, though.
C and C++'s header time complexity hell is not an “implementation detail”, every compiler has to suffer with it. The C preprocessor is a fundamental design problem.
include guards don't really solve this problem, because the preprocess needs to read every line to find the end of the include guard. The pragma once solution works, but it is hard to implement it for every system (what happens when a file has different names but same content)?
Of course, they also recommend using "#pragma once" unless you're really concerned about portability.
Source: https://docs.microsoft.com/en-us/cpp/preprocessor/once?view=...
> The compiler recognizes the include guard idiom, and implements the multiple-include optimization the same way as the #pragma once directive if no non-comment code or preprocessor directive comes before or after the standard form of the idiom:
I would say, that qualifies as "good enough". The amount of headache saved from accidentally having 2 guards with the same name it way more than the requirement to NOT have multiple symbolic paths to the same file used at the same time.
That said, modern compilers just use inode number (and a similar thing on Windows), that covers about 99.9% of real-world systems where you want to build.
This will tell whether pragmas / include guards have largely solved the problem.
Plus on Windows shops we tend to compile C++ libraries into native artifacts, or COM libraries, so unless you are making the whole world from scratch, or doing crazy meta-programing without external templates, do the compile times become a problem.
VC++ modules support is showing quite promising.
Then again I do enjoy having to spend most of my time on Jav/.NET land in what concerns compile times.