C++ Compiler – Why Can’t a Compiler Avoid Importing a Header File Twice?

ccompiler

New to C++! So I was reading this: http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/

Header guards

Because header files can include other header files, it is possible to
end up in the situation where a header file gets included multiple
times.

So we make preprocessor directives to avoid this. But I'm not sure – why can't the compiler just… not import the same thing twice?

Given that header guards are optional (but apparently a good practice), it almost makes me think that there are scenarios when you do want to import something twice. Although I can't think of any such scenario at all. Any ideas?

Best Answer

They can, as shown by new languages that do.

But a design decision was made all those years ago (when the C compiler was multiple independent stages) and now to maintain compatibility the pre-processor has to act in a certain way to make sure old code compiles as expected.

As C++ inherits the way it processes header files from C it maintained the same techniques. We are supporting a old design decision. But changing the way it works is too risky lots of code could potentially break. So now we have to teach new users of the language how to use include guards.

There are a couple of tricks with header files were you deliberately include it multiple times (this does actually provide a useful feature). Though if we redesigned the paradigm from scratch we could make this the non-default way to include files.