View Full Version : How can i prevent class redefinition problem ?
ankurjain
24th May 2006, 13:39
hi all,
suppose there are three files a.h,b.h,c.h
which contain classes a,b,c respectively.
and let c.h included in b.h and b.h included in a.h.
//c.h
class c
{ ....
};
//b.h
#include c.h
class c
{...
}
//a.h
#include b.h
#include c.h
class a
{...
}
On compiling there comes an error of class redeclaration ..... how can we prevent this ?
ankurjain
24th May 2006, 13:46
ok putting the b.h file in #ifndef ... #endif block solved the problem ... :o
mcosta
24th May 2006, 14:18
hi all,
suppose there are three files a.h,b.h,c.h
which contain classes a,b,c respectively.
and let c.h included in b.h and b.h included in a.h.
//c.h
class c
{ ....
};
//b.h
#include c.h
class c
{...
}
//a.h
#include b.h
#include c.h
class a
{...
}
On compiling there comes an error of class redeclaration ..... how can we prevent this ?
The standard way is
Generic header file
#ifndef <FILENAME>_H
#define <FILENAME>_H
class <ClassName>
{
};
#endif // <FILENAME>_H
In example
// a.h
#ifndef a_h
#define a_h
class a
{
};
#endif // a_h
// b.h
#ifndef b_h
#define b_h
#include "a.h"
class b
{
};
#endif // b_h
// c.h
#ifndef c_h
#define c_h
#include "a.h"
#include "b.h"
class c
{
};
#endif // c_h
In this way the second inclusion of "a.h" are ignored by precompiler.
gfunk
24th May 2006, 20:02
If you use Visual C++, you can also try:
#pragma once
at the top of each header file, this makes the compiler read the header just once.
jacek
24th May 2006, 20:50
If you use Visual C++, you can also try:
#pragma once
at the top of each header file, this makes the compiler read the header just once.
Beware that this solution isn't portable.
Put all Class declaration in One generic header file.
such as:
//className.h
#ifndef CLASS_NAME_H
#define CLASS_NAME_H
class a;
class b;
class c;
//....
#endif //CLASS_NAME_H
Powered by vBulletin® Version 4.2.5 Copyright © 2023 vBulletin Solutions Inc. All rights reserved.