C++ Programming Guide

Unnecessary Header File Inclusion

Programs written in C++ typically include many more declarations than do C programs, resulting in longer compilation times. You can reduce the number of declarations through judicious use of several techniques.

One technique is to conditionally include the header file itself, using the macro defined to make it idempotent. This approach introduces an additional interfile dependence.


#ifndef HEADER_H
#include "header.h"
#endif


Note -

System header files often include guards of the form _Xxxx, where X is an uppercase letter. These identifiers are reserved and should not be used as a model for constructing macro guard identifiers.


Another way to reduce compilation time is to use incomplete class and structure declarations rather than including a header file that contains the definitions. This technique is applicable only if the complete definition is not needed, and if the identifier is actually a class or structure, and not a typedef or template. (The standard library has many typedefs that are actually templates and not classes.) For example, rather than writing:


#include "class.h"
a_class* a_ptr;

write:


class a_class;
a_class* a_ptr;

(If a_class is really a typedef, the technique does not work.)

One other technique is to use interface classes and factories, as described in the book Design Patterns: Elements of Reusable Object-Oriented Software, by Erich Gamma, Addison Wesley, 1994.