How to stop access to Global variables in C

Links
Image by PIRO4D from Pixabay

If you have an application made up of multiple source and header files, it’s possible that you use global variables in those source files. Remember, these are variables declared outside of any function.

Now you may not know it, but by default, those variables are visible to other files through what is known as external linkage.

Slap extern on the definition and the compiler and linker will happily use it. For instance in the Asteroids game, there is an extern int variable used in the file asteroids.c.

// external variables
extern int errorCount;

This is declared in the source file lib.c and when all the modules are linked together the linker sees all the compiled symbols and figures out which refers to which.

Making your program robust

If you don’t want global variables in one file to be accessed from another, just add the keyword static in front of the declaration like this.

static int errorCount = 0;
Now then, even though you’ve got the extern, when you compile it you’ll get an error. This is what Visual C++ says.

Severity Code Description Project File Line Suppression State
Error LNK2001 unresolved external symbol _errorCount asteroids D:\writing\Amazon EBooks\GamesProgrammer\publishing\Learn C Games Programming\Windows\Code\asteroids_ch48\asteroids\asteroids.obj 1 
Error LNK1120 1 unresolved externals asteroids D:\writing\Amazon EBooks\GamesProgrammer\publishing\Learn C Games Programming\Windows\Code\asteroids_ch48\asteroids\Debug\asteroids.exe 1

So obviously only do this with global variables that are not going top be referred to. In this case we do refer to errorCount in Asteroids.c so adding the static would make no sense.