#include (rant 1)

My first rant on #include in C++. I”m sure there’ll be more but let’s just start with this one…

#include "level1/level2/level3/level4/filename.h

What are we trying to do here? Let’s say filename.h includes something like:

class MyClass
   int x;
   int y;
   void DoSomething();

Clearly then, what we are trying to do is make the code we’re currently writing or editing have access to the details of the class MyClass.

So why can’t we just say that? Well, in a way we can. If we called the file MyClass.h instead of filename.h then we could potentially have:

#include "MyClass.h"

as long as we’ve set up our compiler’s include path correctly. So what’s the problem?

Well, it’s not really the same thing is it? Unfortunately C++ is designed to use a very old style technique where the source file is king. This is something it inherited from C but that was never really abstracted out. As Ian Joyner puts it in his C++ Critique:

“The programmer must also use #includes to manually import class headers. #include is an old and unsophisticated mechanism to provide modularity. #include is a weak form of inheritance and import. C++ still uses this 30 year old technique for modularisation, while other languages have adopted more sophisticated approaches, for example, Pascal with Units, Modula with modules, Ada with packages. In Eiffel the unit of modularisation is the class itself, and includes are handled automatically. The OOP class is a more sophisticated way to modularise programs.”

The crux of it is that we have here a system where source code effectively defines what other source code is included in a build of a system. A more modular approach is that the source code requests a particular module and we use the build system to define where that module comes from. My problem with C++ is clearly that, if I wanted to move an include file from one place to another then not only would I need to update the build system (i.e. potentially change include paths on my compiler settings) but, in the example above, I would also have to change source code that should not need to be changed!

In essence C++ pollutes the source code with file structure implementation dependencies that should be kept for the build system.

This is truly a poor way to manage code structure.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.