use a variable defined in main from another source file?
is it possible if I define a variable, say...
int oranges = 0;
in main.cpp and alter it like:
1 2
|
cout << "How many? << endl;
cin >> oranges;
|
and have another .cpp file that has a function
eatOranges()
use that variable
oranges
even though it's being defined and messed with in main.cpp?
Yes, here is an example (with parameter passing):
1 2 3 4 5 6 7
|
//Oranges.h
#ifndef _Oranges_Included_
#define _Oranges_Included_
void eatOranges(int numOranges);
#endif
|
1 2 3 4 5 6 7 8 9
|
//Oranges.cpp
#include "Oranges.h"
#include <iostream>
void eatOranges(int numOranges)
{
std::cout << "Eating " << numOranges << " oranges" << std::endl;
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
//Main.cpp
#include "Oranges.h"
#include <iostream>
#include <limits>
int main()
{
int oranges = 0;
std::cout << "How many?" << std::endl;
std::cin >> oranges;
eatOranges(oranges);
std::cout << "Press enter to continue..."<< std::endl;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
return 0;
}
|
You should either to pass this variable as an argument to the function or declare it with external linkage.
Topic archived. No new replies allowed.