c - 存储类声明

标签 c variables static declaration extern

下列声明是否正确?

在任何函数之外:

int a; //external by default
extern int a; //explicitly extern
static int a; //explicity static
const int a; //static by default
static const int a; //explicitly static
extern const int a; //explicitly extern

函数内部:

int a; //auto by default
static in a; //explicity static
const int a; //static by default
static const int a; //explicitly static

最佳答案

关闭。

默认情况下,全局范围内的任何内容(即:函数外部)都是静态的。

例如:

//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 从其他文件访问全局变量,前提是它们没有像上面的示例那样显式声明为 static。

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

请注意,在函数中使用静态变量的情况有限且数量有限,但对于大多数项目而言通常不是一个好主意。

关于c - 存储类声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10455020/

相关文章:

c - 访问冲突错误 C

c - 意外的链接描述文件符号地址

linux - 连接变量的问题,cat 和 cut 命令的结果

c++ - 显式切片派生对象

c - 如何创建一个使用输入 GTK 更改文本的窗口

c - 如何在Windows中获取C中的调用堆栈?

C 编程,存储来自 for 循环的数据

javascript - JS Closure 的变量值

java - 我们必须在静态类上做新的吗

rust - 如何在 Rust 的结构中声明 "static"字段?