Hey I'm creating a text based game and I'm getting really confused when I tried to separate the functions in different cpp files so I can clear my main.cpp file.
the errors I'm having right now are:
Error LNK1169 one or more multiply defined symbols found
Error LNK2005 "int playerchoice" (?playerchoice@@3HA) already defined in main.obj
Error LNK2005 "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > name" (?name@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A) already defined in main.obj
Mission1.cpp
#include "Mission1.h"
#include "functions.h"
Mission1::Mission1()
{
system("cls");
cout << "The thief uses speed magic and you have to catch him before he escapes." << endl;
cout << endl;
switch (playerchoice)
{
case 1:
cout << "You striked him down with your Fire Dragon's Roar" << endl;
break;
case 2:
cout << "You striked him down with your Shadow Dragon's Roar" << endl;
break;
case 3:
cout << "You striked him down with your Iron Dragon's Roar" << endl;
break;
case 4:
cout << "You striked him down with your Lightning Dragon's Roar" << endl;
break;
case 5:
cout << "You striked him down with your Wind Dragon's Roar" << endl;
default:
break;
}
cout << endl;
cin.ignore();
cout << "Press Enter to Continue";
cin.get();
}
Mission1Start::Mission1Start()
{
cout << "das" << endl;
}
The file functions.h defines a global variable: int playerchoice;
The source file main.cpp includes the file functions.h, so when compiled (and turned into an object file) the source file main.cpp defines a global variable: int playerchoice;
The source fileMission1 includes the file functions.h, so when compiled (and turned into an object file) the source file Mission1 defines a global variable: int playerchoice;
When the linker joins together the two object files, it finds that both of them are trying to create a global variable with the same name. This is bad. Don't have two global variables with the same name.
The problem is that you have defined the variables in a header file so they are getting defined multiple times, once for each .cpp file that includes the header file.
If you are using a modern compiler you can solve this problem by making the variables inline.