First, this is a general question
Second: I thought of it because right now it complicated things in a project of mine. Don't worry I got a workaround, but I'd still want to know if there had been another way of solving it.
getting to the question:
I have my main.cpp. I defined some methods and functions in it. I have some other files with other functions and stuff too, but now I need a function that works with temporary variables that are defined in the main.cpp. How can I extend the scope of such a variable so that I can use it in other files also?
From classes, I know that fields can be private or public. But what about this variable? Is it private? public? something else? can I create a getter/setter for this variable? I can't even include the main.cpp in another since it would be recursive and I'd have main defined infinite times then ....)
The main questions would be:
How can I access a variable defined in my main.cpp in another file?
some example code:
in main.cpp:
int var = 0;
int getVar() {
return var;
}
void doVar() {
// sth happens with var
}
int main() {
MyObject myObj;
doVar();
}
in MyObject.cpp:
class MyObject {
void DoSth(){
// NEEDS var from main.cpp, to do sth with it!
// getVar() doesn't work!
// doVar() doesn't work either!
}
}
Forgive me if this is a previously asked or really stupid question, but I was really wondering about that just now
My workaround was that I made doVar and var to members of MyObject (i.e. now its all in the same file MyObject.cpp), but is this the only way?
extern int var;in MyObject.cpp and go with that if you really want a global, but maybe there's a better solution. It's not clear to me what you're trying to achieve. (and the downvote's not mine. I'm out of votes!)privateandpublickeywords only have a meaning inside a class see e.g. here.