Why use Include Guard in C++

They are some potential problems that can be cause by #include  directives. Consider the header file:

// RigidBody.h
#include "coreMath.h"
// ---- Rest of RigidBody declartions

// Scene.h
#include "coreMath.h"
#include "RigidBody.h"

The problem is that the contents of the file coreMath.h were included twice in the same file. This is how it looks after the prepocessor is done with it:

// Scene.cpp
#include "coremath.h"
#include "coreMath.h"

To solve that problem we use include guards. Include Guard prevents the content of the file from being actually seen twice by the compiler. Include Guard is basically a set of preprocessors’s conditional directives at the beginning and end of a header file.

// coreMath.h
#ifndef CORE_H
#define CORE_H

#endif // End of scene.h

If every header files has guards around it, we can guarantee that it is never included twice. The first time preprocessor includes it, the guard symbol is no defined, so it immediately defines it and proceeds to include the rest of the file. The next time we try to include the same file, the guards symbol is already defined and the preprocessor skips that file completely.

Posted in C++

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s