When building I come across these errors:
Error 5 error LNK2005: “int __cdecl numGen(void)” (?numGen@@YAHXZ)
already defined in main.obj
Error 6 error LNK1169: one or more multiply defined symbols found
numGen.cc:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int numGen()
{
int rNum;
srand(time(NULL)); //--Seeds a random number.
rNum = 1 + (rand() % 100);
return rNum;
}
main.cc:
#include <iostream>
#include "NumGen.cc"
int main()
{
std::cout << numGen();
return 0;
}
By
#includeingNumGen.ccin yourmain.ccfile, you are causing the preprocessor to create two files like the following:NumGen.cc:and
main.cc:because the
#includepreprocessor directive just inserts the contents of the file you are including where you are including it (unless of course it’s been included before and is wrapped in an include guard. I’m also assuming that you are compiling bothNumGen.ccandmain.ccon the same command line, so naturally you’ll get a multiply defined symbol error given the functionnumGenis now defined and implemented in both files.What you have to do is forward declare
numGenin a header file, let’s call itNumGen.h:and then put the line
#include "NumGen.h"in bothNumGen.ccandmain.cc.