【问题标题】:How to globaly initialize variable in c and what is the difference between static and extern?如何在c中全局初始化变量,静态和外部有什么区别?
【发布时间】:2020-09-12 04:38:33
【问题描述】:

请解释一下如何在 C 中全局初始化变量作用域以及 static 和 extern 之间的区别

【问题讨论】:

  • 在文件级别,static 表示该变量是文件本地的,对其他文件(编译单元)不可见。 extern 表示它是全局的,对其他文件可见。

标签: c variables scope global-variables local-variables


【解决方案1】:

变量的范围意味着:在哪里可以看到(也就是它在哪里存在)并因此可以访问。

变量的范围取决于它在代码中的定义位置。

变量在在函数之外定义时获得全局作用域。关键字static 可以限制全局变量的范围,使其只能在特定的 c 文件(也称为编译单元)中看到。所以:

file1.c

int gInt1;         // Global variable that can be seen by all c-files

static int gInt2;  // Global variable that can be seen only by this c-file

void foo(void)
{
    int lInt;  // Local variable 

    ...
}

为了使用来自另一个 c 文件的全局变量,你告诉编译器它存在于另一个文件中。为此,您使用 extern 关键字。

file2.c

extern int gInt1;  // Now gInt1 can be used in this file

void bar(void)
{
    int n = gInt1 * (gInt1 + 1);

    ...
}

您经常将extern 声明放入头文件中。喜欢:

file1.h

extern int gInt1;  // Any c-file that includes file1.h can use gInt1

file2.c

#include "file1.h" // Now gInt1 can be used in this file

void bar(void)
{
    int n = gInt1 * (gInt1 + 1);

    ...
}

关于初始化

初始化全局变量与初始化局部变量没有区别。

全局变量和局部变量之间的唯一区别是您没有有初始化程序。在这种情况下,局部变量将保持未初始化,而全局变量将默认初始化(这通常意味着初始化为零)。

file1.c

int gInt1 = 42;         // Global variable explicit initialized to 42

int gInt2;              // Global variable default initialized to 0

void foo(void)
{
    int lInt1 = 42;     // Local variable explicit initialized to 42

    int lInt2;          // Local variable uninitialized. Value is ??
    ...
}

【讨论】:

    【解决方案2】:

    要声明一个全局范围的变量,只需在所有函数之外声明即可。

    初始值-0。

    全局变量的范围:可以在所有函数和文件中使用。

    Life-Till 程序执行。

    extern keyword的使用:

    如果你在一个文件中声明了一个全局变量并想在另一个文件中使用它,那么使用extern 关键字。

    int x=5;        //source file
    
    extrern int x=10;   //any other file
    

    extern 关键字的另一种用法是在程序中声明之前使用 gobal 变量。 示例:

    void main()
    {
     int x
     extern int y;
     x=y;
    } 
    int y=5;
    

    静态变量:

    初始值-0

    范围 - 直到控制保留在块、函数或文件中。

    Life -Till 程序执行。

    void main()
    {
    fun();
    fun();
    fun();
    }
    void fun()
    {
    int x=0;
    x++;
    }
    

    程序结束后 x=3。

    静态变量也可以用作全局变量并在所有函数之外声明 但范围保留在定义它的文件中。 示例:

    static int x=2;
    int main()
    {
     x=5;
    }
    

    就是这样!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-25
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 2013-07-21
      • 1970-01-01
      相关资源
      最近更新 更多