"Already defined in .obj" - what?

This is my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Game.hpp

#include <fstream>

namespace data
{
	unsigned int integer;
	void Load();
}

// Game.cpp

#include "Game.hpp"

void data::Load()
{
	std::ifstream load;
	load.open("savegame.txt");
	load >> integer;
	load.close();
}

// Main.cpp

#include "Game.hpp"

int main()
{
}


(1) error LNK2005: "unsigned int ax::integer" (?integer@ax@@3IA) already defined in Game.obj File: Main.obj
(2) error LNK1169: one or more multiply defined symbols found

I don't understand what the problem is here.

Any help would be appreciated!
Last edited on
try this: load >> data::integer
try this: load >> data::integer

It doesn't help. (Since it's called within a method of the "data" namespace, it does so automatically, it seems.)
Last edited on
@Little Bobby Tales - No, that won't fix the multiply defined symbols.

@OP - At line 7 you're declaring data::integer. game.hpp is included in both game.cpp and main.cpp. Therefore, you've defined data::integer twice. You should avoid defining variables in your header files. If you want a variable to be visible in multiple modules, you need to use the extern keyword. Then define the variable in once and only one .cpp file.

game.hpp:
1
2
3
4
5
 
namespace data 
{ extern unsigned int integer;
... 
}


main.cpp OR game.cpp (but not both)
1
2
3
namespace data
{  unsigned int integer;
}


Last edited on
So... Do I do this, then?:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// Game.hpp

#include <fstream>

namespace data
{
	void Load();
}

// Game.cpp

#include "Game.hpp"

namespace data
{
        unsigned int integer;
}

void data::Load()
{
	std::ifstream load;
	load.open("savegame.txt");
	load >> integer;
	load.close();
}

// Main.cpp

#include "Game.hpp"

int main()
{
}


I place the variables in the .cpp file, but the methods in the .hpp file, or what do you mean? It works, though.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// Game.hpp
#include <fstream>

namespace data
{   extern unsigned int integer;  // declaration
    void Load();
}

// Game.cpp
#include "Game.hpp"
namespace data
{  unsigned int integer;  // definition
} 
void data::Load()
{   std::ifstream load;
    load.open("savegame.txt");
    load >> integer;
    load.close();
}

// Main.cpp
#include "Game.hpp"

int main()
{
} 


There is really no reason to declare integer as extern in game.hpp if you're only ever referencing it within game.cpp.


Last edited on
All right, I think I get it now. Thanks for your help!
Topic archived. No new replies allowed.