I wonder about the use of the static
keyword as scope limiting for variables in a file, in C.
The standard way to build a C program as I see it is to:
- have a bunch of c files defining functions and variables, possibly scope limited with
static
. - have a bunch of h files declaring the functions and possibly variables of the corresponding c file, for other c files to use. Private functions and variables are not published in the h file.
- every c file is compiled separately to an o file.
- all o files are linked together to an application file.
I see two reasons for declaring a gobal as static
, if the variable is not published in the h file anyway:
- one is for readability. Inform future readers including myself that a variable is not accessed in any other file.
- the second is to prevent another c file from redeclaring the variable as
extern
. I suppose that the linker would dislike a variable being bothextern
andstatic
. (I dislike the idea of a file redeclaring a variable owned by someone else asextern
, is it ok practice?)
Any other reason?
Same goes for static
functions. If the prototype is not published in the h file, other files may not use the function anyway, so why define it static
at all?
I can see the same two reasons, but no more.