Pavel Oganesyan
Pavel Oganesyan

Reputation: 6924

Making one header to be needed for several classes inclusion

I have a number of classes and they are quite close to each other like

class A
{
//code
};

class B
{
   A* field;
//code
};

class C: public B
{
//code
};

And so on. And I want to place them in a separate headers (A.h, B.h...) but to avoid adding every one of this header to projects I need a header like myLib.h, that will be just one needed header to include all the classes that I have wrote. Ho do I achieve it?

Also I think not to use #pragma once; and to make it working

#ifndef _MY_LIB_H
#define _MY_LIB_H
#endif

Where should I place it? In every header?

I've tried doing it like

class A;
class B;
...

in myLib.h

but then adding myLib.h to main.cpp is not enough to use A or B objects there. Also, in B.h that

#inlude myLib.h

void someMethod()
{
//field is instance of A
  this.field.otherMethod();
}

causes an error because methods of A are declared in A.h, not in myLib.h.

Sorry for long and tangled question.

Upvotes: 0

Views: 67

Answers (2)

Kirill Kobelev
Kirill Kobelev

Reputation: 10557

Besides using the pattern

#ifndef _A_H
#define _A_H

   ... Stuffs

#endif

in each header, I always add

#ifndef _A_H
#include <A.h>
#endif
#ifndef _B_H
#include <B.h>
#endif
....

to other headers, like myLib.h. This considerably improves the speed of compilation because compiler does not need to load and scan the low level headers if they are already scanned.

I do not add this to my cpp files, because the number of headers in cpp is typically reasonable, while it mich more difficult to track relations between headers.

Upvotes: 2

Jon
Jon

Reputation: 437366

You should use a separate include guard in each of A.h, B.h, C.h:

// Note: not a good name for a guard macro (too short)
#ifndef _A_H
#define _A_H
    // definition of A
#endif

And then MyLib.h becomes simply:

#include<A.h>
#include<B.h>
#include<C.h>

Of course each of your headers should manually include as many of the others as required so that it can stand alone (e.g. C.h would need to include B.h so that the code compiles if someone includes C.h directly).

In some cases you will not need to have one header include another because a forward declaration is enough -- for example in B.h, where an A* member is declared:

#ifndef _B_H
#define _B_H
class A;

class B
{
   A* field;
};
#endif

Upvotes: 2

Related Questions