A note about include guards

Programmers discuss here anything related to FreeOrion programming. Primarily for the developers to discuss.

Moderator: Committer

Post Reply
Message
Author
tzlaine
Programming Lead Emeritus
Posts: 1092
Joined: Thu Jun 26, 2003 1:33 pm

A note about include guards

#1 Post by tzlaine »

Include guards in headers can provide a substantial compile time savings. The guards I refer to guard the header file itself:

Code: Select all

#ifndef _Foo_h_
#define _Foo_h_

... file contents

#endif // _Foo_h_
as well as any headers it may include:

Code: Select all

#ifndef _Foo1_h_
#include "Foo1.h"
#endif

#ifndef _Foo2_h_
#include "Foo2.h"
#endif

.. other includes
Both of these help to dramatically reduce the amount of preprocessing and parsing done during compilation.

However, these techniques are useless in implementation files (.cpp files). They just take up a lot more room and make for a lot more typing, as well as introducing possible errors:

Code: Select all

#ifndef _Foo1_h_
#include "Foo2.h"
#endif

#ifndef _Foo1_h_ // oops!
#include "Foo2.h"
#endif

.. other includes
and cut-n-paste errors are notoriously hard to find. In this case, the error will jump out at you in the form of undefined symbols, but if you look at the includes above and aren't paying attention, you may decide that Foo2.h is being included, and then a) spend an hour trying to convince yourself you're not crazy and/or b) including additional headers that also include the symbols you need, which defeats the purpose of using the guards in the first place.

Post Reply