I'm working on the core of my engine and i'm having a serious link issue in Microsoft Visual c++ express.
To simplify things, what is causing problems is these two header files and each header file has a namespace with a different identifier. Both of these include files actually include each other. No error is obtained from compiling, however on linking, an error shows up saying "X already defined in A.obj". An example is provided below:
HEADER 1
#ifndef HEADER1_H
#define HEADER1_H
#include "header2.h"
namespace Core{
int x, y, z;
}
#endif
HEADER 2
#ifndef HEADER2_H
#define HEADER2_H
#include "header1.h"
namespace GUI{
int x, y, z;
}
#endif
What ends up happening is I get an error stating that the x, y, and z variables were already defined in the first .obj file that was created. I assumed that because the variables are from different namespaces they could not collide. I have header guards as well so the header files don't seem to be included multiple times.
Anyways, any sort of help or advice would be greatly appreciated. I've been stuck on this for around 3 days :P. Also, please let me know if I'm not giving enough information, it is just that my current code is extremely long.
Cheers, Joey
Actually, the problem is that the variables are defined in the header files- it's not that the header files include, is that in each .cpp files that includes the header, all 6 variables are being defined.
Each .cpp file turns into a .o file, and each .o ends up with the variables being defined, which causes the linker errors. What you want to do is use the extern keyword in the headers, that tells the compiler the actually variable is defined elsewhere...
for instance:
namespace Core{
extern int x, y, z;
}
and
namespace GUI{
extern int x, y, z;
}
then, in a cpp file ( in only one cpp file! ) you need define the variable without the extern
namespace Core {
int x, y, z;
}
namespace GUI{
int x, y, z;
}
that will fix your linker errors.
The problem is not that you're including the same variable names in multiple namespaces, it's that you're defining the variables in a header rather than just declaring them. This makes the compiler create one copy of those variables for each of the compilation units that includes the header, and these conflict at link time, which is why you get errors.
Use extern to just declare them in the headers, rather than defining them:
HEADER 1
#ifndef HEADER1_H
#define HEADER1_H
#include "header2.h"
namespace Core{
extern int x, y, z;
}
#endif
HEADER 2
#ifndef HEADER2_H
#define HEADER2_H
#include "header1.h"
namespace GUI{
extern int x, y, z;
}
#endif
And then in the respective .cpp
files for your two headers, put your namespace Core { int x, y, z; }
and namespace GUI{ int x, y, z; }
namespace Foo {... }
, and the contents accumulat - je4d 2012-04-05 00:45