I have read somewhere that we can restrict the scope of global variable to a file only by
using static keyword before variable name. But, when i tried it practically it comes out to be false:
//1st file - file1.c //2nd file - file2.h
#include<file2.h> static int a;
main()
{
fun();
}
fun()
{
printf("%d",a);
}
O/P is 0
Now we do have a global variable a which is declared in file2.h, whose scope is limited to this file only.
Since, we have declared it as static, but still we can access this variable in file1.c. How ??
In restrict the scope of global variable to a file statement, by file they mean compilation unit, i.e. a
.cfile. Your file2.h is included by file1.c and they constitute one compilation unitfile1.Move the variable to a second compilation unit e.g.
file2.c, and you’ll see you can’t access it even withexterndeclaration.