Shared memory architecture - Global variables

I'm putting together a parallel program in pthreads. I'm still kind of new to c-syntax, but is it true that a variable declared outside main() is global? Or is there more to it..?
Yes, it is called a global variable. But you can access a global variable AFTER it is written - E.G.
THIS is valid:
1
2
3
4
5
int GlobalVariable = 0;
int main()
{
 GlobalVariable = 1; // Valid
};

THIS is not:
1
2
3
4
5
int main()
{
 GlobalVariable = 1; // Valid
};
int GlobalVariable = 0;
1
2
3
4
5
6
7
8
extern int GlobalVariable;
int main()
{
    cout << GlobalVariable << endl;
    GlobalVariable = 0;
    cout << GlobalVariable << endl;
}
int GlobalVariable = 1;
Last edited on
Good to know about the "extern" keyword.
Line 8 could also be in a different source file entirely ;)

Note that global variables are discouraged. To help you remember not to use them you can do this:
1
2
3
#define global /##/
//...
global int MyGlobal;
Best reminder ever ;)
Last edited on
Thanks all for clarifying! I'll read up on the extern stuff you mentioned.

L B not using globals makes shared architecture somewhat tedious. ;-)

EDIT
I read a line or two about extern. No need for that in this application.
Last edited on
The problem with global data is the same problem as with public class members - the access is unrestricted. You should at least restrict the access to make it easier to refactor your code.
Last edited on
Globals in a multithreaded environment is even bigger trouble.
L B - The whole point is to make it accessible. As long as I lock the variable when a thread is thinkering with it i should be safe. You know pthread_mutex_lock() etc.

Thanks for your concern!

Disch - Not sure but it seems you mixed up the concept of tedious and big trouble. ;-)
Topic archived. No new replies allowed.