The practice of using include guards in .cpp files was recommended by John Lakos in his book Large-Scale C++ Software Design. I don't know whether any one before him had recommended the practice.
Say you have
A.h:
#ifndef __A__
#define __A__
#include "B.h"
#include "C.h"
// ...
// ...
// ...
#endif
B.h:
#ifndef __B__
#define __B__
// ...
// ...
// ...
#endif
C.h:
#ifndef __C__
#define __C__
// ...
// ...
// ...
#endif
SomeClass.cpp:
#ifndef __A__
#include "A.h"
#endif
#ifndef __B__
#include "B.h"
#endif
#ifndef __C__
#include "C.h"
#endif
When SomeClass.cpp is compiled, the contents of A.h is included. As a by-product of including the contents of A.h, the contents of B.h and C.h are also included. Also, the pre-processor macros __A__
, __B__
and __C__
are defined. When the line
#ifndef __B__
is processed, since __B__
is already defined, the next line is skipped.
If SomeClass.cpp had just:
#include "A.h"
#include "B.h"
#include "C.h"
the file B.h has to be opened and processed. The contents of the file will not be included again due to the include guards but the file has to be opened and closed.
By using the first strategy, you avoid the cost of of opening and closing B.h and C.h. For large scale C++ project, John Lakos asserts, the cost is too much. Hence, the recommendation of using include guards even in .cpp files.