Monday, 15 June 2009

Avoiding Redifinition using #pragma once

Lets write a very simple program where there is main.cpp that includes classA.h and classB.h. classA.h contains class A and classB.h contains class B.



//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//Program to show how to avoid redifinition problems
#include <iostream>
#include "classA.h"
#include "classB.h"

using namespace
std;

int
main()
{

A a;
B b;
a.a = 20; //some stuff not relevant here
b.a = 40; //some stuff not relevant here
return 0;
}

//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//A very simple example class that does nothing
class A
{

public
:
int
a;
int
b;
private
:
int
c;
};
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//A very simple example class that does nothing
#include "classA.h"

class
B :public A
{

private
:
int
d;
};

When we try to compile this, the compiler complains as follows:




To get round this problem, in each of the include file we can use a #define as follows

#ifndef _CLASSA_H_

#define _CLASSA_H

//Some code

#endif //_CLASSA_H

In C++ we can also write #pragma once. Using #pragma once can increase compilation speed and the compilor may optimise the code as the use of pre-processor can be removed. So the class A in our program giving problem can now be modified as follows for the program to compile properly:




//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//A very simple example class that does nothing
#pragma once
class A
{

public
:
int
a;
int
b;
private
:
int
c;
};


No comments:

Post a Comment