Sunday, February 6, 2011

Understanding C++ Include Guard

In C++, include guard is often seen and it has a syntax like this
#ifndef MACRONAME_H
#define MACRONAME_H

....

#endif
The purpose of it is to disallow multiple redefinition. For example.
Person.h
//#ifndef PERSON_H_
//#define PERSON_H_

class Person
{
public:
    Person();
    virtual ~Person();
};

//#endif /* PERSON_H_ */

Person.cpp
#include "Person.h"

Person::Person()
{
}

Person::~Person()
{
}

Employee.h
//#ifndef EMPLOYEE_H_
//#define EMPLOYEE_H_

#include "Person.h"

class Employee : public Person
{
public:
    Employee();
    virtual ~Employee();
};

//#endif /* EMPLOYEE_H_ */

Employee.cpp
#include "Employee.h"

Employee::Employee()
{
}

Employee::~Employee()
{
}

Main.cpp
#include <iostream>
#include "Person.h"
#include "Employee.h"
using namespace std;

int main()
{
    Employee employee;
    return 0;
}

Here, we included the Person.h twice, one in the Employee.h and the other one is in the Main.cpp. This code won't compile because C++ has One Definition Rule. If we uncomment the include guard part in the code, the code will compile just fine.

Microsoft Visual C++ has #pragma once for such purpose, but it's not a standard, thus not portable.

No comments:

Post a Comment