有人能解释一下什么时候应该在头文件中定义的全局变量或常量之前使用 static 关键字吗?
例如,假设我有一个包含以下行的头文件:
const float kGameSpriteWidth = 12.0f;
这是否应该在 const
前面加上 static
?使用 static
的一些最佳实践是什么?
最佳答案
您不应该在头文件中定义 全局变量。 您应该在 .c 源文件中定义它们。
如果全局变量只在一个 .c 文件中可见,则应将其声明为静态。
如果要在多个 .c 文件中使用全局变量,则不应将其声明为静态的。 相反,您应该在所有需要它的 .c 文件包含的头文件中将其声明为 extern。
例子:
例子.h
extern int global_foo;
foo.c
#include "example.h" int global_foo = 0; static int local_foo = 0; int foo_function() { /* sees: global_foo and local_foo cannot see: local_bar */ return 0; }
bar.c
#include "example.h" static int local_bar = 0; static int local_foo = 0; int bar_function() { /* sees: global_foo, local_bar */ /* sees also local_foo, but it's not the same local_foo as in foo.c it's another variable which happen to have the same name. this function cannot access local_foo defined in foo.c */ return 0; }
关于c - 什么时候在全局变量前使用 static 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1856599/