C++ in theory: Bridging Your Classes with PIMPLs
(Page 1 of 4 )
Very often, when a program takes longer to compile after you have made what appear to be trivial changes, the blame can be laid at the door of dependency chains between header files. One change can trigger the need for a massive rebuild. J. Nakamura explains a way to make header files insensitive to any change -- thus saving all that rebuild time -- by using pimpl.
Looking For Problems
Large development projects can become a drain... not just on your brain, but on your valuable time as well. When you notice increasing compilation time after making what you thought to be trivial changes, you can claim to have found a problem (some might say that you are looking for one). The application might run fine and be without bugs, but those increasing build times do not really speed up the development process. They are also very annoying when you are making small changes in a debug cycle.
Most often the cause for these extreme build times can be found in large dependency chains between your header files. Consider the following header files:
// MyBase.h
class MyBase {
public:
int foo();
};
// MyDerived.h
#include “MyBase.h”
class MyDerived : public MyBase {
public:
int bar();
};
If you make a change to MyBase.h (let's assume you need a new private or protected member variable), MyDerived and everything, including its header file, will have to be recompiled as well. You can imagine that in a large project, many header files will be dependent on each other, often many levels deep. At a certain point you will notice that you are becoming reluctant to make changes to a class, simply because these changes will trigger a massive rebuild (and might evoke some unpleasant primitive reactions in your colleagues).
There are tools available to analyze these dependencies. Personally I prefer to use Doxygen, which is used to generate documentation from sources. Doxygen can use ‘dot’ from GraphViz to generate nice pictures of header file dependencies. Best of all, it is free!

There are ways to minimize the dependency problem -- for example, by forbidding coders to include header files in header files! But even so, your changes to MyBase.h will trigger a rebuild of MyDerived.cpp, since that is the file that includes the MyBase header now.
Wouldn't it be nice to be able to make the header file insensitive to any change? We would like to prevent recompilation when making changes to a private interface. This is where we use pimpl for [Sutter].
Next: The Private Implementation >>
More C++ Articles
More By J. Nakamura