tags:

views:

43

answers:

2

I have a static variable in source file test_1.c declared as:

static char var1 = 0;

I need to access the current value of this variable from source file test_2.c. So, I did something like:

In test_1.c

static char var1 = 0;
volatile char var_another = var1;

and in test_2.c, I declare the variable var_another as extern and access it:

extern volatile char var_another;

Is this the right way to do it?

+3  A: 

static and extern are mutually exclusive. If you want to access your static char var1 from a different file, you'll have to remove the static and just make it a regular global. You don't need volatile at all.

Alternatively, you can make an accessor function that returns the value of static char var1 and use that from your other module.

Side note: externs and exported function prototypes should generally go in header files.

Nathon
+2  A: 

No! The whole point of static (in this context) is that you're stating that the variable is only visible from this translation module.

If you don't want this behaviour, then don't declare it as static. Put char var1 = 0; in your source file, and extern var1; in the associated header file.

More generally, don't do this at all. Accessing global variables between source files is probably a recipe for disaster.

Oli Charlesworth