Declaring a variable in a different file

I want to declare a couple of variables that I may be able to use in multiple projects.
I decided to do that is an function in a cpp file.
Now if I want to access those two variables, how can I do so?

EDIT:
I think I was a bit unclear.
What I meant is:
a.h
 
void something();


a.cpp
1
2
3
4
5
6
void something()
{
   int a, b;
   a = 10; 
   b = 15;
}


Now if I want to use a & b in a file b.cpp, is there a way to do that?
Note: I am not using the same variables as I used in this example of course


Last edited on
Declaring a variable in a function is useless. You won't be able to access it.
.. Well, you might be, if you declare it as static and have the function return a reference to it.

The usual (bad) way to do this is to declare the variables in a.cpp and then declare the same variables in b.cpp as extern. a.cpp : int x; and b.cpp : extern int x;. Bad, because if you change something in a.cpp, you'll need to change all other files too.

Another (better) way is
1
2
3
4
//a.h
struct Global{
   static int x;
};

1
2
3
//a.cpp
#include "a.h"
int Global::x;

1
2
3
//b.cpp
#include "a.h"
//use Global::x any way you like 


Though it would be best to avoid globals if you can.
Well, I did the static part but didn't return the reference to it.
I tried the extern method as well, but it was giving me a linker error.
I will try the struct method. Thanks a lot.

EDIT:
The struct method did the work!
Thanks a lot...
Last edited on
Usually you'd do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//a.h
extern int x;

//a.cpp
#include "a.h"

int x = 0; // no extern as this is the definition
// variables at file scope are automatically zeroed,
// but I init all variables out of habit

//b.cpp
#include "a.h"
//use Global::x any way you like 
void UseX()
{
    cout << x
}
 


Andy

P.S. Beware of the difference of "static" in the class/struct sense and the file scope sense!
Last edited on
Topic archived. No new replies allowed.