Engine Engine - 23 days ago 6
C Question

Issues with a static variable in C

say I have 4 files.

file1.h
file1.c
file2.h
file2.c


in
file1.h
I have a variable :

static short mode=0;


in
file1.c
:

#include "file1.h"
...............
if ( mode ==0)
do stuff
else {
do something else
}


the problem I have is that I can only change
mode
value in
file2.c


in file2.h I include file1.h and in the source file2.c, I change the value of to
1
but this has no influence on it in
file1.c

Answer

When you write a line like

static short mode=0;

in a .h file and the .h file is included in multiple .c files, you effectively create multiple short mode variables, one in each .c file that ends up including the .h file.

If you want to have one variable, make it extern, make sure to define it in only one .c file.

in file1.h:

// Just the declaration in the .h file.
extern short mode;

in file1.c:

// The definition in only one .c file.
short mode = 0;