C语言-static、extern

static 存储类

static 存储类指示编译器在程序的生命周期内保持局部变量的存在,而不需要在每次它进入和离开作用域时进行创建和销毁。因此,使用 static 修饰局部变量可以在函数调用之间保持局部变量的值。
static 修饰符也可以应用于全局变量。当 static 修饰全局变量时,会使变量的作用域限制在声明它的文件内。
static 是全局变量的默认存储类,以下两个变量 (count 和 road) 都有一个 static 存储类。

static int Count;
int Road;   //默认存储类为static

main()
{
    printf("%d\n", Count);
    printf("%d\n", Road);
}

static 修饰全局变量和局部变量的应用:

#include <stdio.h>

/* 函数声明 */
void func1(void);

static int count=10;        /* 全局变量 - static 是默认的 */

int main()
{
    while (count--) 
    {
        func1();
    }
    return 0;
}

void func1(void)
{
/* 'thingy' 是 'func1' 的局部变量 - 只初始化一次
 * 每次调用函数 'func1' 'thingy' 值不会被重置。
 */                
    static int thingy=5;
    thingy++;
    printf(" thingy 为 %d , count 为 %d\n", thingy, count);
}

运行结果:

thingy 为 6 , count 为 9
thingy 为 7 , count 为 8
thingy 为 8 , count 为 7
thingy 为 9 , count 为 6
thingy 为 10 , count 为 5
thingy 为 11 , count 为 4
thingy 为 12 , count 为 3
thingy 为 13 , count 为 2
thingy 为 14 , count 为 1
thingy 为 15 , count 为 0

extern 存储类

extern 存储类用于提供一个全局变量的引用,全局变量对所有的程序文件都是可见的。当您使用 ‘extern’ 时,对于无法初始化的变量,会把变量名指向一个之前定义过的存储位置。
当您有多个文件且定义了一个可以在其他文件中使用的全局变量或函数时,可以在其他文件中使用 extern 来得到已定义的变量或函数的引用。可以这么理解,extern 是用来在另一个文件中声明一个全局变量或函数。
extern 修饰符通常用于当有两个或多个文件共享相同的全局变量或函数的时候,如下所示:

//**** 第一个文件:main.c ********************
#include <stdio.h>                         

int count;  //变量定义
extern void write_extern();

int main()
{
    count = 5;
    write_extern();
}
//******************************************


//**** 第二个文件:support.c *****************
#include <stdio.h>

extern int count;   //其他文件引用变量的声明

void write_extern(void)
{
    printf("count is %d\n", count);
}

//******************************************

在这里,第二个文件中的 extern 关键字用于声明已经在第一个文件 main.c 中定义的 count。现在 ,编译这两个文件,如下所示:
$ gcc main.c support.c
这会产生 a.out 可执行程序,当程序被执行时,它会产生下列结果:

count is 5

转自: C 存储类

猜你喜欢

转载自blog.csdn.net/BjarneCpp/article/details/80217065