views:

74

answers:

2

I am trying to address this issues because I can not seem to find a good resource online that does so.

I do not fully understand the issue cause I never got it resolved so I will try to describe it as best as possible.

Awhile ago I had an issue where headers were being ignored because "They were called once already and therefore when they were called again by another document, it was being ignored and therefore an error was being thrown"

I never fully understood that because you can call a header more then once without errors being thrown

header1.h

#ifndef _FCLASS_
#define _FCLASS_
class firstClass {
     ...//declaration
}

#endif

header2.h

#ifndef _SCLASS_
#define _SCLASS_

#include "header1.h"

class SecondClass:firstClass{
     ...//declaration
}

#endif

header3.h

#ifndef _TCLASS_
#define _TCLASS_

#include "header1.h"
class thirdClass:firstClass{
     ...//declaration
}
#endif

In the above example, the header1 class was called twice, and no errors should of been thrown. Even though header1 was declared once, it could be used by multiple headers.

So my question is , in what scenarios, can a header actually be ignored by a document if it was already declared once.

Does this type of issue only apply to .cpp files that include headers ??

+2  A: 

I can think of one scenario. If header1.h has sections that are excluded by conditional compilation and those conditions change by declarations in subsequently included header files. Later inclusions of header1.h will be skipped by its include guard and it won't be able to declare the conditional sections which could lead to errors.

Amardeep
+5  A: 

This most commonly happens when there's a header cycle (two headers including each other being the most likely case).

Just for illustration, real examples are usually more complex.

A.h:

#ifndef A_INCLUDED
#define A_INCLUDED

#include "B.h"

class A
{
};

class C
{
    B b;
}
#endif

B.h:

#ifndef B_INCLUDED
#define B_INCLUDED

#include "A.h"

class B : public A
{
};
#endif

In this case, regardless of which header you include, there's a circular dependency that prevents it from compiling. If you include A.h, it includes B.h. B.h then includes A.h but the include guard prevents it from being included again. So then it continues compiling B.h and fails when it doesn't know about class A. The reverse situation applies if including B.h first.

EDIT: I should have mentioned that this is typically solved by refactoring logic out of one or both headers into another header, and/or using forward declarations instead of actual includes.

Mark B
I heard of this before. Perhaps that was my problem. Then again, I did try to check for this and still got the issue. unless I missed something.
numerical25