Using variable from other files.

Dec 17, 2010 at 1:53am
I've noticed that my draw function in my header doesn't work because I'm trying to use a variable in the header that is used in my main.cpp file. Is it possible to put these functions in other files other than the main.cpp file? Will using another .cpp file work? Why would you use multiple .cpp files? I just don't want my files starting to flood with text...
Last edited on Dec 17, 2010 at 1:54am
Dec 17, 2010 at 2:27am
Don't use globals. Pass the variable you need to the function. Then it will work in any file. And it will work with any variable, which makes your code more reusable.

1
2
3
4
5
6
7
8
9
10
11
12
13
// BAD

int foo;

void somefunc()
{
  cout << foo;
}

int main()
{
  somefunc();
}


1
2
3
4
5
6
7
8
9
10
11
12
// GOOD

void somefunc(int foo)
{
  cout << foo;
}

int main()
{
  int foo;
  somefunc(foo);
}
Last edited on Dec 17, 2010 at 2:36am
Topic archived. No new replies allowed.