I have created a text based battle simulation in visual studios 2010 and am having
a large amount of trouble turning it into multiple header and .cpp files. My plan is to set it up into two .cpp files and one header file. The first header file for simplicities sake looks like this.
#include<iostream>
#include"combat.cpp"
using namespace std;
int main()
{
combat(); //The main function in combat.cpp
}
If I understand it right this file will load combat.cpp and then call the function combat from the combat.cpp file. The combat.cpp file looks like this. As a note the battleFunctions.h header file called below contains all variables and functions that need to be used by combat.cpp.
function definitions...
function definitions...
function definitions...
int combat()
{
battle logic and function calls...
}
every time I try to compile I get some of the following errors about all of my variables. The only way I have been able to fix the errors is by moving everything back to one .cpp file where it all worked initially.
1>Main.obj : error LNK2005: "int tHolder2" (?tHolder2@@3HA) already defined in combat.obj
1>Main.obj : error LNK2005: "int playWait" (?playWait@@3HA) already defined in combat.obj
1>Main.obj : error LNK2005: "int palyWait2" (?palyWait2@@3HA) already defined in combat.obj
1>Main.obj : error LNK2005: "int promptStat" (?promptStat@@3HA) already defined in combat.obj
1>Main.obj : error LNK2005: "bool runLogic" (?runLogic@@3_NA) already defined in combat.obj
1>Main.obj : error LNK2005: "int playWait2" (?playWait2@@3HA) already defined in combat.obj
1>Main.obj : error LNK2005: "int tHolder3" (?tHolder3@@3HA) already defined in combat.obj
1>Main.obj : error LNK2005: "int tHolder4" (?tHolder4@@3HA) already defined in combat.obj
1>Main.obj : error LNK2005: "int timeSum" (?timeSum@@3HA) already defined in combat.obj
Thank you very much for your time! I have spent several hours looking for a solution and have been so far extremely unsuccessful.
You don't include .cpp files.
By default, every .cpp is one translation unit and will be compiled separately.
You can't have any global symbols in more than one translation unit, but by including combat.cpp in main.cpp, you now have the symbols defined in combat.cpp in both translation units.
See also: http://en.wikipedia.org/wiki/One_Definition_Rule
You fix the problem by creating a header file for combat.cpp that just contains the following declaration: int combat();
Now when you include combat.h in main.cpp, the above declaration will tell the compiler that there is such a function somewhere. The linker will look for it at the linking stage and find it in the translation unit that consists of combat.cpp.
Thank you Athar! At first what you said didn't make sense, but it pushed me in the right direction and my program is now compiling correctly. Thanks Again!!!