When to use static keyword before global variables

2020-01-27 00:05发布

Can someone explain when you're supposed to use the static keyword before global variables or constants defined in header files?

For example, lets say I have a header file with the line:

const float kGameSpriteWidth = 12.0f;

Should this have static in front of const or not? What are some best practices for using static?

标签: c static keyword
8条回答
叛逆
2楼-- · 2020-01-27 00:26

static before a global variable means that this variable is not accessible from outside the compilation module where it is defined.

E.g. imagine that you want to access a variable in another module:

foo.c

int var; // a global variable that can be accessed from another module
// static int var; means that var is local to the module only.
...

bar.c

extern int var; // use the variable in foo.c
...

Now if you declare var to be static you can't access it from anywhere but the module where foo.c is compiled into.

Note, that a module is the current source file, plus all included files. i.e. you have to compile those files separately, then link them together.

查看更多
贼婆χ
3楼-- · 2020-01-27 00:30

static renders variable local to the file which is generally a good thing, see for example this Wikipedia entry.

查看更多
淡お忘
4楼-- · 2020-01-27 00:32

Rule of thumb for header files:

  • declare the variable as extern int foo; and put a corresponding intialization in a single source file to get a modifiable value shared across translation units
  • use static const int foo = 42; to get a constant which can be inlined
查看更多
看我几分像从前
5楼-- · 2020-01-27 00:32

The static keyword is used in C to restrict the visibility of a function or variable to its translation unit. Translation unit is the ultimate input to a C compiler from which an object file is generated.

Check this: Linkage | Translation unit

查看更多
一纸荒年 Trace。
6楼-- · 2020-01-27 00:36

Yes, use static

Always use static in .c files unless you need to reference the object from a different .c module.

Never use static in .h files, because you will create a different object every time it is included.

查看更多
疯言疯语
7楼-- · 2020-01-27 00:41

The correct mechanism for C++ in anonymous namespaces. If you want something that is local to your file, you should use an anonymous namespace rather than the static modifier.

查看更多
登录 后发表回答