有人可以解释一下何时应该在头文件中定义的全局变量或常量之前使用 static 关键字吗?
例如,假设我有一个包含以下行的头文件:
const float kGameSpriteWidth = 12.0f;
这个应该有static
在...前面const
或不?使用的一些最佳实践有哪些static
?
你不应该define头文件中的全局变量。
您应该在 .c 源文件中定义它们。
Example:
-
示例.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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)