0

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.

Pavel Oganesyan
  • 6,774
  • 4
  • 46
  • 84

2 Answers2

2

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
Jon
  • 428,835
  • 81
  • 738
  • 806
  • Also you can avoid some inclusions by using forward declarations. – Ed Heal Jul 06 '12 at 08:13
  • @EdHeal: Thanks for the input, updated the answer to clarify. – Jon Jul 06 '12 at 08:16
  • 1
    Strictly speaking, names like `_A...` are reserved for the implementation, it's probably better to choose a different convention for header guards. http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier – BoBTFish Jul 06 '12 at 08:17
2

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.

Kirill Kobelev
  • 10,252
  • 6
  • 30
  • 51