A variable declared globally is said to having program scope
A variable declared globally with static keyword is said to have file scope.
For example:
<
Variables declared as static
cannot be directly accessed from other files. On the contrary, non-static
ones can be accessed from other files if declared as extern
in those other files.
Example:
foo.c
int foodata;
static int foodata_private;
void foo()
{
foodata = 1;
foodata_private = 2;
}
foo.h
void foo();
main.c
#include "foo.h"
#include
int main()
{
extern int foodata; /* OK */
extern int foodata_private; /* error, won't compile */
foo();
printf("%d\n", foodata); /* OK */
return 0;
}
Generally, one should avoid global variables. However, in real-world applications those are often useful. It is common to move the extern int foo;
declarations to a shared header file (foo.h in the example).