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:
int x = 0; // **program scope**
static int y = 0; // **file scope**
static float z = 0.0; // **file scope**
int main()
{
int i; /* block scope */
/* .
.
.
*/
return 0;
}
What is the difference between these two?
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 <stdio.h>
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).