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/
Related
This question already has answers here:
linkage error:multiple definitions of global variables
(1 answer)
Multiple definition error on variable that is declared and defined in header file and used only in its cpp file
(3 answers)
Closed 2 years ago.
I have recently started learning c++ after learning a good amount of Javascript.
I'm pretty sure that the problem I am facing has to do with scope/how many times the header file is #included, but I need some clarification.
If you look at what I have - you can see that I have "int input" commented out in input.hpp, and I have it actually declared in input.cpp within the scope of the getInput() function. Can someone explain in detail why I am able to compile the way it is written here, but it won't compile if I switch where "int input" is declared? NOTE: The error I get is " multiple definition of `input' "
Also, I know this is a long post so if I need to ask this in another post please tell me. Since I am new to C++, have I separated my files correctly?
These are my files:
main.cpp
#include <iostream>
#include "add.hpp"
#include "input.hpp"
int x = getInput();
int y = getInput();
int main()
{
std::cout << add(x, y) << std::endl;
return 0;
}
add.cpp
#include "add.hpp"
#include <iostream>
int addCalc (int x, int y)
{
return (x + y);
}
std::string add (int x, int y)
{
return (std::to_string (x) + " + " + std::to_string (y) + " = " + std::to_string (addCalc (x, y)));
}
add.hpp
#ifndef add_hpp
#define add_hpp
#include <iostream>
int addCalc(int x, int y);
std::string add(int x, int y);
#endif
input.cpp
#include "input.hpp"
#include <iostream>
int getInput()
{
int input;
std::cout << "Enter a number: " << std::endl;
std::cin >> input;
return input;
}
input.hpp
#ifndef input_hpp
#define input_hpp
#include <iostream>
int getInput();
//int input;
#endif
Any and all comments would be appreciated.
Thanks in advance!
This question already has answers here:
When to use extern in C++
(4 answers)
Closed 3 years ago.
I've got aud.ccp, aud.h, geist.ccp, geist.h. In geist.ccp I've got a variable which needs to get to aud.ccp.
If I got:
int x = 5;
in geist.ccp, how can I achieve it, that a 8 gets represented in the console when I use
cout << x+y << endl;
as well as
cin >> y; // ofc I enter 3 here.
in aud.ccp.
Edit:
I wrote:
int x
in the public part of geist.h
and I wrote:
x = 5;
in geist.cpp.
Finaly I wrote
extern int x;
in aud.cpp
But somehow I do not get the result I want
You need to declare the variable in a public scope of one module:
int x;
and declare its use in another one:
extern int x;
Then both modules, when linked together, will use the same variable.
It's most conveniently done with the defining declaration (with an optional initializer) placed in a .cpp module, and the extern declaration put into a .h file. Then each module, both the one defining the variable and those importing it, see the same extern declaration, which guarantees the declaration is same as an actual definition of the variable.
You have to care about "redefinition x variable Error" in your code.
You can Try this method:
geist.h:
#ifndef GEIST_H
#define GEIST_H
int x {5};
#endif
geist.cpp:
#include "geist.h"
#include <iostream>
using namespace std;
void printname()
{
cout << "The X value is" << x <<"\n";
}
aud.h:
#ifndef AUD_H
#define AUD_H
extern int x;
void Add_X_with_User_Desire();
#endif
aud.cpp:
#include "aud.h"
#include <iostream>
using namespace std;
void Add_X_with_User_Desire()
{
int y{0};
cout << "Please Enter an Integer Number: "<< "\n";
cin >> y;
cout << "y + x: " << x+y<<"\n";
}
and finally main function:
stack59228825.cpp:
#include <iostream>
#include "aud.h"
int main()
{
std::cout <<"X variable in main function is:" <<x << "\n";
Add_X_with_User_Desire();
x = 10;
std::cout << "targetVariable in main function is:" << 10 << "\n";
Add_X_with_User_Desire();
}
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 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
I am sorry but i don't know why this algorithm is not working.
The error at compiling is : "Reference to 'function' is ambiguous " and is on y = function() line, where I am calling the function
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define PI 3.141
float function(int g, int m, int s, float z)
{
using namespace std;
z = (g + m/60.0 + s/3600.0)*PI/180.0;
return z;
}
int main()
{
using namespace std;
float y;
int g,m,s;
cout << "g = ";
cin >> g;
cout <<"m = ";
cin >> m;
cout<<"s= ";
cin >>s;
y = function();
cout << "y= " << y << endl;
//cout<< (g + m/60.0 + s/3600.0)*PI/180.0 << endl;
return 0;
}
Vers2 - updated:
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#define PI 3.141
float function(int g, int m, int s)
{
//using namespace std;
float z = (g + m/60.0 + s/3600.0)*PI/180.0;
//std::cout << z <<std::endl;
return z;
}
int main()
{
// using namespace std;
float y;
int g,m,s;
std::cout << "g = ";
std::cin >> g;
std::cout <<"m = ";
std::cin >> m;
std::cout<<"s= ";
std::cin >>s;
function();
// std::cout << "y= " << y << std::endl;
//cout<< (g + m/60.0 + s/3600.0)*PI/180.0 << endl;
return 0;
}
There is a member function in std and you inserted it into your namespace. Avoid using using namespace std;; you can import what you need this way:
using std::cout;
using std::cin;
I am getting a similar type of error while I used "prev" as a global variable of Node* type. Just renaming it with "prevv" solved issue in my case.
It is mostly due to the name of a "variable or function" is present in some library you used.
I can't reproduce your error message (for any of your versions with 3 different compilers), but the basic problem with your code is that you apparently assume the g,m,s-variables in your main functions are automatically used as parameters when you call function() just because they happen to have the same name.
This is NOT the case!
The variables inside your main and in the parameter list of function() are completely independent entities. The proper way to call the function and passing the right values is this:
y=function(g,m,s);
This basically copies the values stored inside the main g,m,s variables into the g,m,s parameters, which are accessed inside the function and after the function has completed, it then copies the value stored inside the variable you "return" from the function (here z) into the variable y.
This should work whether you are using using namespace std; or not, as your function has a completely different signature, But I'd still highly recommend to choose another name for your function.
I hope this doesn't sound like an insult, but I highly recommend that you read a introductory book about c++ programming, as it seems you are missing out on basic concepts of the language.