Is there a way to make a variable in C only accessible to the file in which it was declared?
I am asking this because I remember reading somewhere that it's possible to do t开发者_Go百科hat, but I really can't remember how to do that. Is it possible, or am I just imagining?
Declare it as a static global.
static int foo;
int incrementfoo()
{
return ++foo;
}
Using the static
keyword will give the global variable internal linkage, meaning that the name will not be visible to other translation units. However, note that this differs from what you asked for in that:
- The name could still be accessed from other files included in the same translation unit (files included via the
#include
directive). - The variable can still be accessed by other translation units (modules) in your program if they can obtain its address, for example if there's a function in the same translation unit as your
static
variable which returns a pointer to it.
static is the word you are looking for
The static
keyword does that; by contrast, the extern
keyword can let you import other variables from other files.
精彩评论