Regarding header inclusions

Hello,
I was thinking about the extern variables and why if we define a variable inside a header (and include that header in multiple files), this will result in linker error, even if we use inclusion guards.
I thought that these macros will prevent that part of the code from compilation.


And another thing, is there a difference between #include <OurClass> in the header and #include <OurClass> in source ?

For example, if we have class A with pointer of class B, we could write forward declaration in class A header

1
2
3
4
class B;
class A {
B *pointer;
}


but we can also directly include the header of B.
Or when we need B in the source of A, we can include B in the header or in the source.
Which is best and why ?

Thank you in advance :)
This might not give you all the answers, but a good read anyway :
http://www.cplusplus.com/forum/articles/10627/
To answer your first question,

Consider a header file header.h that has the following global variable declaration:
int x;

Consider two source files, f1.cpp and f2.cpp, both of which include header.h.

Suppose that f1.cpp is compiled before f2.cpp. When f1.cpp is compiled, the compiler reads header.h
and instantiates, as part of the object file f1.obj (f1.o), an integer variable named x. Now f2.cpp gets
compiled. Again, the compiler reads header.h and instantiates, as part of the object file f2.obj (f2.o),
another integer variable named x. Now when f1.obj and f2.obj get linked into the final executable,
there are two separate instantiations of the same variable, x. Hence a linker error.

This happens because f1.cpp and f2.cpp are compiled separately... that is, you do something like:
g++ f1.cpp -o f1.o
g++ f2.cpp -o f2.o

By the time you run g++ the second time, it doesn't remember that f1.cpp already read header.h.

Include guards are useful only when f1.cpp includes a.h and b.h, both of which include header.h.
In this case, header.h gets read and parsed only once thanks to the include guards.

Second question: always forward declare if possible. It helps to avoid circular include dependencies.
Thank you for your answers...

jsmith, this is interesting. About the include guards.
Actually they work through the #define macro. But where is the variables (if I can call them like this) defined with #define actually stored ?

If the guards memory is lost across multiple compilation units, then this is not cool.

Regards
#defines are processed by the preprocessor and aren't ever seen by the compiler proper, so the answer to your question is that they are stored temporarily in the preprocessor's "symbol table", which is wholly in memory.
I see.
Thank you very much for your answers.

Regards
Topic archived. No new replies allowed.