Predeclarations instead of #include
How do we make our code compile quickly?
It helps to understand a little bit about how the C Preprocessor works when executing #include directives. Often C++ programs can get quite slow to compile if the header files in the project have more #includes of other header files than is necessary.
The problem is that one header file might include 5 other header files, but these each include 5 other header files each which then include 5 each and if each header file is on average 30 lines then after the C Preprocessor has run we get:
5 * 5 * 5 * 30 = 3750 lines of code
So this means the C++ compiler now has to parse almost 4000 lines of code instead of the apparent 30 lines. If we could cut the number of header files that each file includes to fewer - say 2 each then let's look at the numbers:
2 * 2 * 2 * 30 = 240 lines of code
i.e. less that 10% of the amount before - which means the C++ compiler has less than 10% of the code to parse - we have a lot less disc reading and we probably get a speed up of 10-20 times faster compilation.
Pre-declarations are tool to reduce the number of includes we need to do in header files by allowing us the shift the #include statements into the cpp files. Having #includes in cpp files doesn't have the same terribly multiplier effect we see above because cpp files are not (or should not!) included by other cpp files.
Pre-declarations improve compile time and should be used in place of including the full file whenever possible.
// This predeclares the class
class COLstring;
// This is an include for the class COLstring which gives us the complete definition
#include <COL/COLstring.h>
// This doesn't require #include - a pre declaration is enough
// because the size or methods of COLstring do not need to be known at this time
void FOOfunc(const COLstring& Input);
This applies only to header files. The CPP files will require the #include statement. Even in header files, there are 2 general cases where pre-declarations will not work.
If the compiler needs to know how much space to allocate for a member variable of the class
The compiler needs to know how much space to allocate for variable SomeStringVariable
If any class methods have been called on the member variable
The compiler needs to have information about the method clear() We can do without the include if we are just declaring a pointer to a member variable, since pointers are of a standard size which is known to the compiler (32/64 bit allocation usually) .
Â