[Moved][Solved] Compiler header guard problem
-
Hi!
I'm having problem compiling my project. It seems that header guards aren't working as they should ( or I messed up something).
I've a header file globals.h, for global variables. I'm including it in several other files.When compiling, I get errors, that variables were already declared. The number of errors is the same as the number of times I included globals.h.
Has someone ever experienced similar, or knows how to solve this problem?
Regards,
Jake -
I uploaded the example on 2shared:
http://www.2shared.com/file/ZVJnyK7f/Example.html? -
Is there a reason you include <code>Globals.h</code> within <code>Globals.h</code>?
@
#ifndef GLOBALS_H
#define GLOBALS_H#include <QList>
#include <QString>#include "Globals.h" // <---
struct SVar
{
QString name;
QString value;
};QList<SVar *> varList;
#endif // GLOBALS_H
@ -
No.
Look like I accidentally added it in there to.
But I'm getting the same result even if I remove it.And also, if I know correctly, header guards should prevent problems with including file in itself and compiling file again if included in several different places.
EDIT:
I'm also open for other ideas how could I implement few variables visible everywhere. I've tried static class, but I have a problem calling QList variable out. Passing pointers unfortunately isn't an option.
But it also bugs me, why header guards aren't working. -
I moved this to the C++ Gurus forum, as it's nothing Qt related.
You don't run into a header guard issue, those work as expected. And you don't get a compiler error that a variable is already declared, but the linker errors that a symbol is defined twice.
This is caused by this line in your header file:
@
QList<SVar *> varList;
@As the header is finally included in two .cpp files (via their "own" header files), the compiler generates two objects of the same name. As you did not put it into a namespace or the like they both reside as a global variable - and voilĂ : a name clash.
Fortunately it's easy to circumvent this:
Change Globals.h to
@
extern QList<SVar *> varList;
@and add to one and only one source file (e.g. main.cpp) this line:
@
QList<SVar *> varList;
@The change to the header file makes the variable just a declaration, so that the compiler just knows that there is a global variable of the name varList somewhere. And as you acutally need a physical incarnation of the variable, you will have to add it to some source file. Which source file doesn't matter, but main.cpp is a good candidate for such things.