Like Java, the symbols (variables and functions) in C have a scope, which is the part of code within which they are accessible.
The scope system of C is only simpler than that of Java. There is no syntax for a package in C.
- global scope
- can accessed from anywhere in the program
- file scope
- can be accessed only within the file in which it is defined
- block scope
- can only be accessed within the block of code in which it is defined
Keyword static
applied to a symbol defined outside any code block
in the current file gives the symbol file scope.
Keyword extern
means the definition of the symbol is to be
found outside this file (so compiler doesn’t complain.)
dangers
Note: scope of a symbol is independent of its type information. If you write code that uses a global function whose prototype has not been provided, the compiler may build the program anyway (it will usually complain though). The result can be bad.
best practice
- keep scope of symbols as tight as possible,
- use header files to communicate type info of shared symbols.