Declaring Global Variables and/or Workaround

I'm using Code::Blocks and the GNU compiler, and I have a multi-file program. I have multiple functions in different files using the same variables. How do I make a global variable, or work around this?
Why not just pass the variable as an argument to the other functions?

1
2
3
4
5
6
7
8
9
void foo(int &num) {
      num+=5;
}

int main(void) {
      int a = 5;
      foo(a);
      std::cout << a << '\n';
}

http://c2.com/cgi/wiki?GlobalVariablesAreBad
Last edited on
Yes, this is an excellent idea. But in case I need to test something, how do you make a global variable in a Multi-File project.
You will need to use the "extern" keyword in every file that uses that global variable.
http://msdn.microsoft.com/en-us/library/0603949d(v=vs.80).aspx

main.cpp:
1
2
3
4
5
6
7
8
9
#include <iostream>
#include "test.h"

int global = 2;

int main(void) {
     foo();
     std::cout << global << '\n';
}

test.h:
1
2
3
4
5
extern int global;

void foo(void) {
     global+=2;
}
Last edited on
Okay, what if I need to return a string?

1
2
3
4
5
6
7
8
void getName(){

string name;
cin << name;
return name;

//How can I do this?
}
Last edited on
Declare that getName returns type string.
1
2
3
4
5
string getName()
{ string name;
   cin << name;
   return name;
}
oh, you can do that? Interesting, I will investigate. (New to C++)
Topic archived. No new replies allowed.