Advertisement

Already defined in main.obj???

Started by May 09, 2002 04:38 AM
3 comments, last by shakazed 22 years, 7 months ago
I´m trying to make a model loader in DX8 and I´ve encountered a problem i´ve never seen before. My code is split up in two files "dx.cpp" and "main.cpp". I also have e .h file named "dx.h" with prototypes and globals. I can compile the code but not link it, when I get to that part I´m introduced to mr"error LNK2005: "unsigned long g_dwNumMaterials" (?g_dwNumMaterials@@3KA) already defined in main.obj". What may the problem be? sHaKaZeD
You''re including dx.h in two seperate source files, which causes the compiler to define all symbols in dx.h twice (once for dx.cpp and once for main.cpp). Hence, when the linker tries to combine all the code, it sees double .

You can fix this by adding the following lines to dx.h:

#ifndef PROJECTNAME_DX_H
#define PROJECTNAME_DX_H

/* All DX.h code goes here

#endif

(Replace ''PROJECTNAME'' with the name of your project, or whatever else you like).

Now, when you recompile the code, PROJECT_DX_H will get defined the first time the compiler processes dx.h. Then, on the second run the #ifndef statement will prevent the compiler from processing dx.h again.

good luck,

jofferman.
Advertisement
Hmm, now I seem to get the error in dx.obj instead...

sHaKaZeD
remove the global variable definitions from the .h file. put them in a cpp file. This is what is happening:

// suppose this is ur .h file
int g_someVar;

now when this is included in main.cpp, the variable g_someVar is defined. When the .h file is included in dx.cpp, g_someVar is defined again by the compiler since the compiler cant see the g_someVar in main.cpp, but when the linker tries to link the references to g_someVar, it sees 2 g_someVar, so it generates an error.

To remove the error:
dont define variables in header files, only declare them:

// declaration in .h
extern int g_someVar;

// definition in .cpp, say main.cpp
int g_someVar;

the extern modifier tells the compiler that g_someVar is defined already somewhere. So now the compiler will reference that g_someVar instead of defining a new one.

Hope that helps.
Try REBUILD ALL

This topic is closed to new replies.

Advertisement