I have a question about scope, and declaring variables in C++ [duplicate] - c++

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!

Related

Transfering Variable between different files [duplicate]

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();
}

Compiling two projects together in Code Blocks

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/

c++, Connecting Hpp and Cpp [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
/*Header.h file*/
#include <iostream>
using namespace std;
int main(){
/*Menu*/
/*case1:
int x;
cout << "Input ammount:";
cin >> x
sugarcake(x)*/
/*case2:
something else
*/
}
/*sugarcake.cpp file*/
#include <iostream>
#include "Header.h"
using namespace std;
void sugarcake(int x) {
cout << (x * 0.75) << "st egg" << endl;
cout << (x * 0.75) << "dl sugar" << endl;
cout << (x * 0.5) << "tsk vanillasugar" << endl;
cout << (x * 0.5) << "tsk blabla" << endl;
cout << (x * 0.75) << "dl wheatflour" << endl;
cout << (x * 18.75) << "gram butter" << endl;
cout << (x * 0.25) << "dl water" << endl;
}
How do i make this work or have i understood it completely wrong? (Started out with C++ yesterday so please be kind and i haven't been able to find any clear answer that works for me elsewhere)
TL DR: Call the function sugarcake(int x) in sugarcake.cpp inside the Header.h
You should not put code in the header file, instead use two source (.cpp) files, and let the header file only contain a declaration of (in your case) the sugarcake function.
So the header file should look something like
// These first two line (and the last line of the file) is part of
// a header include guard (see https://en.wikipedia.org/wiki/Include_guard)
#ifndef HEADER_H
#define HEADER_H
void sugarcake(int x);
#endif // HEADER_H
The sugarcake.cpp file:
#include <iostream>
#include "header.h" // Technically we don't need to include the header
// file here, but it's always a good idea to do
// anyway
void sugarcake(int x) {
...
}
And finally the main.cpp file:
#include <iostream>
#include "header.h"
int main() {
int x;
std::cin >> x;
sugarcake(x);
}
How to build this depends on your environment, but if you're using GCC from the command line then you do like this
$ g++ -Wall -Wextra main.cpp sugarcake.cpp -o sugarcake
The -Wall and -Wextra options are to enable extra warnings, always a good idea. The -o options tells g++ what to name the executable program it creates. The two source files are the files you just created.
We use header files to describe functions which will be used after in another occasion per say.
So I will show how I organize my functions in the header files:
/* header.h
* include guards below, it is very import to use it to be sure you'r not
* including things twice.
*/
#ifndef HEADER_H
#define HEADER_H
// I write function prototypes in the header files.
int sum(int &a, int &b);
#endif // HEADER_H
The definition of the function is written in the header.cpp
// header.cpp
#include "header.h"
int sum(int &a, int &b)
{
int total = a + b;
return total;
}
To use that function in main.cpp you just have to include the header.cpp
// main.cpp
#include <iostream>
#include "header.h"
int main(int argc, char *argv[])
{
int a = 5;
int b = 4;
int total = sum(a, b);
std::cout << "The total sum of the 4 and 5 numbers is: " << total << std::endl;
}
See how it is made? Then you can compile the cpp files and it will work!

Can anyone explain my error from code blocks C++ [duplicate]

This question already has answers here:
Problems importing libraries to my c++ project, how to fix this?
(2 answers)
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 7 years ago.
I'm trying to create a classes in separate files using codeblocks. I get the error in function '_start' undefined reference to 'main'. I'm sure its a linkage problem but can't see where. In my program I’m trying to get a die, let the user decide how many sides the dice has, then roll the die a user specified amount of times.
die.h file///////////////////////////////////
#include <iostream>
#include <string>
#ifndef DIE_H
#define DIE_H
using namespace std;
class die{
public:
die();//function prototype
int numsides;//member
void setNumsides(int numsides_);//setter
int getNumsides();// getter for size of dice
int value;
void setValue(int value_, int numsides_);
int getValue();
int roll;
void setroll(int roll_);
int getroll();
};
#endif// DIE_H
die.cpp//////////////////////////////////////////
#include "die.h"
#include <iostream>
#include <string>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
using namespace std;
die::die()
{
//ctor
}
void die::setroll(int roll_)
{
roll=roll_;
}
int die::getroll()//amount o rolls
{
cout << "enter the ammont of rolls you would like" << endl;
cin >> roll;//amount of rolls you want
return roll;
}
void die::setValue(int value_, int numsides_)
{
value=value_;
numsides=numsides_;
}
int die::getValue()//get value function
{
//int roll;
value = (rand() % numsides) + 1;//sets roll value
return value;
}
void die::setNumsides(int numsides_)
{
numsides=numsides_;
}
int die::getNumsides()//get num of sides
{
cout << "how big of a dice would you like to roll " << endl;
cin >> numsides;//use this to determine dice
if(numsides < 4){//if dice is less than 4
cout << "Error has to be bigger than " << numsides << endl;
numsides = 6;//change to six sided dice
}
return numsides;
}
exercise1.cpp my main class/////////////////////////////////////
#include <iostream>
#include <stdlib.h> /* srand, rand */
#include <time.h>
#include "die.h"
using namespace std;
int main()
{
die mydice;//create an object dice
mydice.getNumsides();//gets sides of dice
mydice.getValue();//gets amount of rolls
mydice.getroll();//rolls the dice value times
return 0;
}

Reference to ' ' is ambiguous

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.