开发者

Is there a way to make a variable in C only accessible to the file in which it was declared?

开发者 https://www.devze.com 2023-04-05 22:08 出处:网络
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 r

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消