May 5, 2014 at 4:46pm UTC
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 May 5, 2014 at 4:49pm UTC
May 5, 2014 at 4:56pm UTC
try this: load >> data::integer
May 5, 2014 at 5:09pm UTC
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 May 5, 2014 at 5:09pm UTC
May 5, 2014 at 5:11pm UTC
@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 May 5, 2014 at 5:13pm UTC
May 5, 2014 at 5:30pm UTC
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 May 5, 2014 at 5:31pm UTC
May 5, 2014 at 5:38pm UTC
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 May 5, 2014 at 5:39pm UTC
May 5, 2014 at 6:12pm UTC
All right, I think I get it now. Thanks for your help!