c - "File scope"和 "program scope"有什么区别

标签 c scope storage-class-specifier

全局声明的变量被称为具有程序作用域
使用 static 关键字全局声明的变量被称为具有文件范围。

例如:

int x = 0;             // **program scope**   
static int y = 0;      // **file scope**  
static float z = 0.0;  // **file scope** 

int main()  
{  
   int i;   /* block scope */  
   /* .
      .
      .
   */ 
   return 0;  
}  

这两者有什么区别?

最佳答案

不能从其他文件直接访问声明为 static 的变量。相反,如果在其他文件中声明为 extern,则可以从其他文件访问非 static

例子:

foo.c

int foodata;
static int foodata_private;

void foo()
{
    foodata = 1;
    foodata_private = 2;
}

foo.h

void foo();

主.c

#include "foo.h"
#include <stdio.h>

int main()
{
    extern int foodata; /* OK */
    extern int foodata_private; /* error, won't compile */

    foo();

    printf("%d\n", foodata); /* OK */

    return 0;
}

一般来说,应该避免使用全局变量。但是,在实际应用中,这些通常很有用。将 extern int foo; 声明移动到共享头文件(示例中的 foo.h)是很常见的。

关于c - "File scope"和 "program scope"有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14027317/

相关文章:

c++ - 是否有可能在未包含在任何其他文件中的文件中使用 extern 变量?

c - 谁决定寄存器存储类的实际存储?

c - 声明说明符和声明符

c - valgrind 在打印分配的字符串时报错

JavaScript OOPS 问题

ruby-on-rails - 示波器的真正好处是什么

ruby-on-rails-3 - 我可以在 Rails 中将常见的 ActiveRecord 范围(范围)与模块一起使用吗?

c - 在C中循环语句中循环并替换变量的值?

Python在另一个cmd窗口中重启脚本

c - 在 MSVS 2012 Express 中构建 OpenCl 示例时出现问题。没有找到头文件,但找到路径等...看起来不错