Transfering Variable between different files [duplicate] - c++

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

Related

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

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!

IntelliSense: "count" is ambigous

#include "stdafx.h"
#include <iostream>
using namespace std;
void func(void);
static int count = 10; /* Global variable */
int main() {
while(count--) {
func();
}
return 0;
}
// Function definition
void func( void ) {
static int i = 5; // local static variable
i++;
cout << "i is " << i ;
cout << " and count is " << count << endl;
}
can't seem to fix this, just learning and reading Storage class in tutorialspoint.com . is this Visual Studio issue? because the code is working on Code::Blocks
There is a "count" function in std namespace, so it collides with you variable
You have several options:
1. Rename your variable to something else
2. Use "::count" instead of "count" (:: means global namespace and not std)
3. Don't do "using namespace std;", instead write "std::" in-front of everything that comes from std, for example: "std:cout", "std::endl"

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/

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.

Using a header file, initialization file, and main file for structs in C++

I am having difficulty executing a program that I wrote with structs. My program has a header file, an initialization file, and a main file. When I compiled it, the compiler complained and later I found out that I forward declared my struct name as Company but initialized it using company so I changed it to Company but still the compiler complains after I did this. How can I fix this? Any help will be greatly appreciated. Below is my code for my three files:
structs.h:
#ifndef STRUCTS_H
#define STRUCTS_H
struct Company{
double salary;
int workers;
int bosses;
}
#endif
initialization.cpp:
Company a = {1200340.99, 30000, 3};
Company b = {500320.85, 5000, 2};
main.cpp:
#include <iostream>
#include "structs.h"
void PrintInfo(Company company){
using namespace std;
cout << "salary: " << Company.salary << endl;
cout << "workers: " << Company.workers << endl;
cout << "bosses: " << Company.bosses << endl;
}
int main(){
PrintInfo(a);
PrintInfo(b);
return 0;
}
You need a ; after the definition of struct Company
In PrintInfo you need to reference the object company (lowercase c) and not the class Company (uppercase C), e.g.
cout << "salary: " << company.salary << endl; // lowercase c
cout << "workers: " << company.workers << endl; // lowercase c
cout << "bosses: " << company.bosses << endl; // lowercase c
As a and b is initialized (globally) in a different source file you must redeclare them with external linkage in the source file that need to access them using the extern keyword, e.g.
// main.cpp
#include <iostream>
#include "structs.h"
extern Company a;
extern Company b;
/* ... */
Consider initializing a and b where they are used instead:
int main() {
Company a = {1200340.99, 30000, 3}; // Init here.
Company b = {500320.85, 5000, 2}; // Init here.
PrintInfo(a);
PrintInfo(b);
// return 0; // Unnecessary in main function.
}
In function PrintInfo, as you are not modifying the argument you should pass the class Company as reference to const to avoid copying, i.e. declare the function using this:
void PrintInfo(const Company& company)
A structure requires a ';' at the end
struct Company{
double salary;
int workers;
int bosses;
};
In addition to the other answers, the code in main.cpp knows nothing about a and b in your initialization.cpp.
You need to either add an extern declaration in structs.h or move those into main.cpp.
But, you should also consider not making them global variables, like this:
int main()
{
Company a = {1200340.99, 30000, 3};
Company b = {500320.85, 5000, 2};
PrintInfo(a);
PrintInfo(b);
return 0;
}