关闭。
默认情况下,全局范围内的任何内容(即:函数外)都是静态的。
例如:
//main.c
int myVar; // global, and static
int main(void) {
...
return 0;
}
//morecode.c
extern int myVar; //other C files can see and use this global/static variable
但是,如果您在全局范围内将某些内容显式声明为静态,则它不仅是静态的,而且仅在该文件中可见。其他文件看不到。
//main.c
static int myVar; // global, and static
int main(void) {
...
return 0;
}
//morecode.c
extern int myVar; // compiler error; "myVar" can only be seen by
// code in main.c since it was explicitly
// declared static at the global scope
此外,默认情况下没有什么是“外部”。您通常使用 extern 从其他文件访问全局变量,前提是它们没有像上面的示例中那样显式声明为静态。
const 仅表示数据不能更改,无论其范围如何。它并不意味着外部或静态。有些东西可以是“extern const”或“extern”,但“extern static”并没有真正意义。
作为最后一个示例,此代码将构建在大多数编译器上,但它有一个问题:myVar 总是被声明为“extern”,即使在技术上创建它的文件中也是如此。不好的做法:
//main.c
extern int myVar; // global, and static, but redundant, and might not work
// on some compilers; don't do this; at least one .C file
// should contain the line "int myVar" if you want it
// accessible by other files
int main(void) {
...
return 0;
}
//morecode.c
extern int myVar; //other C files can see and use this global/static variable
最后,如果您还不熟悉这篇文章,您可能希望涵盖各个级别的范围。它可能对您有所帮助和信息丰富。祝你好运!
Terminology definition - Scope in C application
在我看来,回答我这个关于范围问题的人做得很好。
另外,如果你在函数中声明了一些静态的东西,那么值会在函数调用之间保持不变。
例如:
int myFunc(int input) {
static int statInt = 5;
printf("Input:%d statInt:%d",input,statInt);
statInt++;
return statInt;
}
int main(void) {
myFunc(1);
myFunc(5);
myFunc(100);
return 0;
}
输出:
Input:1 statInt:0
Input:5 statInt:1
Input:100 statInt:2
请注意,在函数中使用静态变量的情况有限且数量有限,因此对于大多数项目来说通常不是一个好主意。