I'm attempting to practice some coding in my free time (combining a number of different interests of mine to help keep myself engaged) and I've encountered a odd error that I can't find the answer to. I have 4 files that I'm working with, two header files, one class definition file and a main file. I'm fairly confident I'm not including the Dice.h file more then once (however that is where the error points to and I'm not sure anymore, hence this question). What have I bungled here to produce these errors?
The error codes
Error 3 error LNK1169: one or more multiply defined symbols found (file path trimmed)
Error 2 error LNK2005: "int __cdecl dice(int,int)" (?dice##YAHHH#Z) already defined in Creature.obj (file path trimmed)
The filepath: c:\Users\Username\documents\visual studio2010\Projects\RPGTest\RPGTest\RPGTest.(error 3 referenced a .exe file, error 2 referenced a .obj file).
The code itself:
Dice.h
#ifndef SET_DICE_H_
#define SET_DICE_H_
#include <iomanip>
#include <iostream>
#include <stdlib.h>
using namespace std;
int dice(int number, int sides){
int total=0, dice;
srand(time(NULL));
int results=0;
do {
dice = rand()%sides+1;
total+=dice;
number--;
} while (number > 0);
results = total;
return results;
}
#endif
Creature.h
#ifndef CREATURE_H_
#define CREATURE_H_
#include <iomanip>
#include <iostream>
#include "Dice.h"
using namespace std;
class Creature {
public:
Creature(int,int,int,int,int,int,int,int,int,int,int,int);
void set_hp();
void set_saves();
void set_ac();
void set_bab();
void set_name();
void update_hp(int);
void update_ac(int);
void update_fsave(int);
void update_rsave(int);
void update_wsave(int);
int get_ac();
int get_hp();
int get_fsave();
int get_rsave();
int get_wsave();
int get_bonus(int);
int get_bab();
string get_name();
private:
int strength, dexterity, constitution, intellegence, wisdom, charisma;
int bab, fbsave, rbsave, wbsave;
int hdnum, hdsize;
int hp, fsave, rsave, wsave, ac;
string name;
};
#endif
Creature.cpp
#include "Creature.h"
#include <math.h>
#include <iostream>
using namespace std;
Creature::Creature(int strength,int dexterity,int constitution,
int intellegence,int wisdom,int charisma,int bab,int fbsave,
int rbsave,int wbsave,int hdnum,int hdsize){
strength = strength;
dexterity = dexterity;
constitution = constitution;
intellegence = intellegence;
wisdom = wisdom;
charisma = charisma;
bab = bab;
fbsave = fbsave;
rbsave = rbsave;
wbsave = wbsave;
hdnum = hdnum;
hdsize = hdsize;
}
int Creature::get_bonus(int stat){
int bonus = floor((double(stat)-10)/2);
return bonus;
}
void Creature::set_ac(){
ac=10+get_bonus(dexterity);
}
void Creature::set_hp(){
hp = dice(hdnum,hdsize) + get_bonus(constitution)*hdnum;
}
void Creature::set_saves(){
fsave = fbsave + get_bonus(constitution);
rsave = rbsave + get_bonus(dexterity);
wsave = wbsave + get_bonus(wisdom);
}
void Creature::set_bab(){
bab = hdnum;
}
void Creature::set_name(){
cout << "Please enter a name for this creature: ";
cout << "\nSorry! I don't work yet!";
cout << "\nInstead all creatures are named Larry!\n";
name = "Larry!";
}
void Creature::update_hp(int input){
hp = hp + input;
}
void Creature::update_fsave(int input){
fsave = fsave+input;
}
void Creature::update_rsave(int input){
rsave = rsave+input;
}
void Creature::update_wsave(int input){
wsave = wsave+input;
}
void Creature::update_ac(int input){
ac = ac+input;
}
int Creature::get_ac(){
return ac;
}
int Creature::get_hp(){
return hp;
}
int Creature::get_fsave(){
return fsave;
}
int Creature::get_rsave(){
return rsave;
}
int Creature::get_wsave(){
return wsave;
}
int Creature::get_bab(){
return bab;
}
RPGTest.cpp
#include "Creature.h"
#include <math.h>
//#include "Dice.h"
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int str = dice(3,6), dex = dice(3,6), con = dice(3,6), intel = dice(3,6), wis = dice(3,6), cha = dice(3,6);
int fbs = dice(1,6), rbs = dice(1,6), wbs = dice(1,6);
int hdn = dice(1,10), hds = 8, bab = dice(1,8);
cout << "Welcome to RPG Creature Tester v0.1\n";
cout << "This .exe file is meant to test the creature class functions and definitions.\n";
cout << "This will be done by randomly generating and displaying a creature.\n";
cout << "What you don't see right now is the random generation of a creature.\n";
cout << "Once it's finished, the \'statsheet\' will be shown.\n";
cout << "Cheers!\n\n";
Creature potato (str, dex, con, intel, wis, cha, bab, fbs, rbs, wbs, hdn, hds);
potato.set_ac();
potato.set_hp();
potato.set_name();
potato.set_saves();
cout << "OUTPUT BRICK YAY\n";
cout << "Str: " << str << endl;
cout << "HP: " << potato.get_hp() << " AC: " << potato.get_ac() << " Fort/Reflex/Will Save: " << potato.get_fsave() << "/" << potato.get_rsave() << "/" << potato.get_wsave();
return 0;
}
Since I'm mainly self-taught I'm happy for any other advice but my main issue is that I'm not sure why I'm getting the "multiple" definition error. I did some research into other questions with similar error messages but I didn't see anything that immediately jumped out at me as "the answer".
Thanks all!
C++ works by compiling single translation units and then linking them together.
This means that each source file gets compiled on its own. Since the #include directive basically inserts all the code included, in your situation you end up having multiple translation units which define
int dice(int number, int sides) {
...
}
Compilation goes through fine but, when linking, multiple definition of this function are found so this generates the error.
To solve this problem you have two ways:
declare int dice(int, int) in a header file but define (implement it) in a source file
keep the definition as it is but prepend static to it. This tells the compiler that each translation unit will get its own dice method. This solution, although tempting, leads to binary size increase since you will have multiple implementation of the same method
Related
So I'm unable to create a substring cut using ranges. I am making an airport program where you feed the program a txt.file and it has to divide the lines I get from it into different strings. For instance, I have the following text data:
CL903 LONDON 41000 14.35 08906 //number of flight, destination, price, etc.
UQ5723 SYDNEY 53090 23.20 12986
IC5984 TORONTO 18030 04.45 03260
AM608 TOKYO 41070 18.45 11315
so the first string will be on the lines of this (variables are in Spanish):
numVuelo[n] = M[n].substr(0,5)
this line will work perfectly, but when I move to the next one (from 7 to 14), it tells me that it's out of range, even though It's between the 0 and 31st values of the length of the string.
M[n] gets all of the strings on the text, I'm using Codeblocks and a class style with header and all. I'll copy the code below...
This is my header Vuelo.h:
#ifndef VUELO_H
#define VUELO_H
#include <iostream>
#include <fstream>
#include <string>
#define NUM_FLIGHTS 10
using namespace std;
class Vuelo
{
public:
Vuelo(int N);
virtual ~Vuelo();
void setM();
void setNumVuelo(string _numVuelo, int n);
void setDestino(string _destino, int n);
void setPrecio(string _precio, int n);
private:
string M[NUM_FLIGHTS];
string numVuelo[NUM_FLIGHTS];
string destino[NUM_FLIGHTS+1]; //somehow "destino" doesn't work without the +1 but everything else does
float precio[NUM_FLIGHTS];
Then, on another code called Vuelo.cpp I have the following
#include "Vuelo.h"
Vuelo::Vuelo(int N)
{
M[N] = { };
numVuelo[N] = { };
destino[N] = { };
precio[N] = { };
}
Vuelo::~Vuelo()
{
//nope
}
void Vuelo::setM()
{
int c = 1;
string s;
ifstream F ("flights.txt");
if(F.is_open())
{
while (!F.eof())
{
getline(F,s);
M[c] = s;
cout << M[c] << endl;
c++;
}
//sets all values
for(c = 0; c < NUM_FLIGHTS; c++)
{
setNumVuelo(M[c],c);
setDestino(M[c],c);
setPrecio(M[c],c);
}
F.close();
}
else
{
cout << "ERROR document wasn't found" << endl;
}
}
void Vuelo::setNumVuelo(string _numVuelo, int n)
{
numVuelo[n]= _numVuelo.substr(0,5); //this works
cout << numVuelo[n] <<endl;
}
void Vuelo::setDestino(string _destino, int n)
{
destino[n] = _destino.substr(7, 13); //PROBLEM HERE
cout << destino[n] << " " << destino[n].length() << endl;
}
void Vuelo::setPrecio(string _precio, int n)
{
string p = _precio.substr(15,19); //PROBLEM HERE
precio[n] = atof(p.c_str());
cout << precio[n] <<endl;
}
And finally my main looks like this:
#include "Vuelo.h"
#include <iostream>
#include <fstream>
#include <string>
#define NUM_FLIGHTS 10
using namespace std;
int main()
{
cout << "Bienvenido, reserva tu vuelo!" << endl;
cout << "-----------------------------------" << endl;
Vuelo* flight = new Vuelo(NUM_FLIGHTS);
flight->setM();
return 0;
}
Thanks :)
im new to C++ language.
So I was assigned to split an existing file into three source code: swap.h, swap.cpp and source3.cpp
Existing File:
#include <iostream>
void get_numbers (int&, int&);
void swap_values (int&, int&);
void show_results (int, int);
int main () {
int first_num, second_num;
get_numbers (first_num, second_num);
swap_values (first_num, second_num);
show_results (first_num, second_num);
return 0;
}
void get_numbers (int& input1, int& input2) {
using namespace std;
cout << "Enter two integers: ";
cin >> input1 >> input2;
}
void swap_values (int& variable1, int& variable2) {
int temp;
temp = variable1;
variable1 = variable2;
variable2 = temp;
}
void show_results (int output1, int output2) {
using namespace std;
cout << "In reverse order the numbers are: "
<< output1 << " " << output2 << endl;
}
swap.h contains function prototypes
swap.cpp contains function implementations
source3.cpp contains the main function
for swap.h:
#pragma once
#ifndef swap_h
#define swap_h
void get_numbers(int&, int&);
void swap_values(int&, int&);
void show_results(int, int);
#endif
for swap.cpp
#include <iostream>
void get_numbers(int& input1, int& input2) {
using namespace std;
cout << "Enter two integers: ";
cin >> input1 >> input2;
}
void swap_values(int& variable1, int& variable2) {
int temp;
temp = variable1;
variable1 = variable2;
variable2 = temp;
}
void show_results(int output1, int output2) {
using namespace std;
cout << "In reverse order the numbers are: "
<< output1 << " " << output2 << endl;
}
for source3.cpp:
#include "stdafx.h"
#include "swap.h"
int main()
{
int first_num, second_num;
get_numbers(first_num, second_num);
swap_values(first_num, second_num);
show_results(first_num, second_num);
return 0;
}
When I debug the program, it says: "Unable to start program 'C:\User......'
The system cannot find the file specified. What am I doing wrong?
Since your code compiles successfully, but cannot be started, you probably have problems related to your debugging environment.
Also, you don't need #ifdef, #define, and #endif once you have #pragma once.
If what you provided is the whole code, you didn't include swap.h in swap.cpp. Therefore you have the definition of the functions, but no declaration. Although I would imagine another error or at least a warning here. Try to fix that.
If it doesn't work, try building the Release Version. Does it compile? Does it start? And when it is starting, does it do anything? If what I mentioned before is the problem, I would expect the program to just run to the end, without doing anything.
If the problem lies with swap.h in the main File, make sure it is in the same location, or the include paths point to the directory which contains it. Same goes for stdafx.h
Also, you don't need #pragma once and #ifndef #define and #endif. Get rid of either of those, I recommend using #ifndef #define and #endif, because #pragma once is not supported everywhere. But for you it shouldn't matter.
I'm learning C++ and tutorial asks me to add another project to what I have now.
Also I'm asked to use forward declaration so I can make use of that added file.
Here is my main project:
#include <iostream>
#include "io.cpp"
using namespace std;
int readNumber();
void writeResult(int x);
int main() {
int x = readNumber();
int y = readNumber();
writeResult(x + y);
return 0;
}
here's the added file called io.cpp:
#include <iostream>
using namespace std;
int readNumber() {
cout << "Enter a number: ";
int x;
cin >> x;
return x;
}
void writeResult(int x) {
cout << "Sum of your numbers is " << x << endl;
}
![And here's a screenshot so you can see what error I'm getting which talks about multiple definition and you can see where those two files are added.
According to the tutorial my code is okay but compiler complains. Why ?]1
In codeblocks, when creating a new class, it should automatically header file. Programming with header files is the best practice out there. Here's the code I tried and it worked, with io.h.
main.cpp
#include <iostream>
#include "io.h"
using namespace std;
io inOut;
int main()
{
int x = inOut.readNumber();
int y = inOut.readNumber();
inOut.writeResult(x + y);
return 0;
}
io.h
#ifndef IO_H
#define IO_H
class io
{
public:
int readNumber();
void writeResult(int);
};
#endif
io.cpp
#include <iostream>
#include "io.h"
using namespace std;
int io::readNumber()
{
cout << "Enter a number: ";
int x;
cin >> x;
return x;
}
void io::writeResult(int x)
{
cout << "Sum of your numbers is " << x << endl;
}
I used codeblocks to compile the code written above, and it worked perfectly.
Well as turns out when adding more cpps they're not supposed to be #included on the top. That's what makes compiler say that function is being defined multiple times. All I had to do was just get rid off that one line.
Here's my source:
http://www.cplusplus.com/forum/beginner/44651/
I have a project that consists of 2 CPP files (main.cpp and Car.cpp) and a header file (Car.h). The program is meant to allow a user to enter the model, make, and speed of a car and displays the modified speed. My issue is that when I compile the project, I receive a "1 unresolved externals" issue like so:
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Car::Car(void)" (??0Car##QAE#XZ) referenced in function _main
1>C:\Users\Shaidi\Desktop\Classes\CIST 2362\Projects\main\Debug\main.exe : fatal error LNK1120: 1 unresolved externals
Here is the main.cpp file:
// main.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Car.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string make;
int model, speed;
Car c;
//user input and assignment for make, model, and speed
cout << "Enter the make of the car: " <<endl;
cin >> make;
c.setMake(make);
cout << "Enter the model of the car: " <<endl;
cin >> model;
c.setYearModel(model);
cout << "Enter the speed of the car: " <<endl;
cin >> speed;
c.setSpeed(speed);
//print make and model
cout << "Car make: " << c.getMake() <<endl;
cout << "Car model: " << c.getYearModel() << endl;
cout << "Car speed: " << c.getSpeed() <<endl;
//loops to calculate and print acceleration and braking
for (int i = 0; i < 5; i ++){
cout << "Car speed after acceleration: " <<c.accelerate() <<endl;
}
for (int i = 0; i < 5; i ++){
cout << "Car speed after braking: " <<c.brake() <<endl;
}
return 0;
} //end main
Here is the Car.cpp file:
// Car.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Car.h"
#include <cstdlib>
#include <string>
#include <iostream>
using namespace std;
Car::Car(int y, string m)
{
string make = m;
int year = y;
speed = 0;
}
void Car::setYearModel(int y)
{
yearModel = y;
}
void Car::setSpeed(int s)
{
if (s >= 0){
speed = s;
} else {
cout << "Invalid speed";
exit(EXIT_FAILURE);
}
}
void Car::setMake(string m)
{
make = m;
}
int Car::getYearModel()
{
return yearModel;
}
int Car::getSpeed()
{
return speed;
}
string Car::getMake()
{
return make;
}
int Car::accelerate()
{
return speed + 5;
}
int Car::brake()
{
return speed - 5;
}
And here is the Car.h file:
#ifndef CAR_H
#define CAR_H
#include <string>
using namespace std;
class Car
{
private:
std::string make;
int yearModel;
int speed;
public:
Car();
Car(int, std::string);
void setYearModel(int);
void setSpeed(int);
void setMake(std::string);
int getYearModel() ;
int getSpeed() ;
int accelerate() ;
int brake() ;
std::string getMake() ;
};
#endif // CAR_H
You miss the implementation of default constructor of Car().
class Car
{
public:
// There is no implementation.
Car();
}
You've declared Car::Car() but never defined it. Either add a definition to the .cpp file, or remove the declaration from the header.
For example:
Car::Car()
{
}
It looks like you have defined the default constructor for car but have not implemented it. Then you declared a variable of type car which would require it to be implemented. Adding the code that Kerrek has above to the .cpp file should do the trick :)
So I have some code in couple of files:
cells.cpp:
#include "cells.h"
#include <iostream>
using namespace std;
char convertIntChar (int symbolNumber)
{
char charR;
switch (symbolNumber)
{
case 0:
charR='0';
break;
// lust of case code here
case 63:
charR='\\';
break;
}
return charR;
}
class cell
{
public:
int iPosition;
char chPosition;
cell ()
{
static int i = -1;
i++;
chPosition=convertIntChar (i);
iPosition=i;
cout << " " << iPosition; //two lines of code to test
cout << " " << chPosition; //constructor
}
protected:
};
main.cpp
#include <iostream>
#include "cells.h"
#include "pointer.h"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
createPointer();
cell cells[64];
return 0;
}
And comeplytly a cells.h
#ifndef CELLS_H_INCLUDED
#define CELLS_H_INCLUDED
#pragma once
class cell
char convertIntChar(int symbolNumber);
#endif // CELLS_H_INCLUDED
There I have an erros that sounds like
//filepath\|5|error: two or more data types in declaration of 'convertIntChar'|
||=== Build finished: 1 errors, 0 warnings (0 minutes, 7 seconds) ===|
What can it be. Sorry for noob question anyway.
First, this forward declaration needs a semi-colon:
class cell;
// ^
Second, you cannot use a forward declaration here. main.cpp needs to see the cell class definition. So you should put the definition in cells.h. For example:
cells.h:
#ifndef CELLS_H_INCLUDED
#define CELLS_H_INCLUDED
class cell
{
public:
int iPosition;
char chPosition;
cell ();
};
char convertIntChar(int symbolNumber);
#endif
cells.cpp:
#include "cells.h"
#include <iostream>
char convertIntChar (int symbolNumber)
{
char charR;
// as before
return charR;
}
cell::cell ()
{
static int i = -1;
i++;
chPosition=convertIntChar (i);
iPosition=i;
std::cout << " " << iPosition; //two lines of code to test
std::cout << " " << chPosition; //constructor
}
You have class cell in the cpp file which should go into the .h file.
Then in cells.h you are missing a ; after class cell.
Insterad of the forward declaration in cell.h, put the class there.