目录
1.关键字 static
源文件与头文件
static修饰全局变量
static修饰局部变量
写在最后:
平时我们在练习的时候,都只会开一个用来测试的源文件,
但是,当我们在写一个项目的时候,例如扫雷、三子棋等等,
我们就会分装成三个以上的文件进行编写 。
例:
test.c文件中:
#define _CRT_SECURE_NO_WARNINGS 1#include "Show.h"int main()
{//创建结构体变量A a1 = { 10 };printf("%d\n", n);printf("%d\n", a1.a);show();return 0;
}
Show.c文件中:
#define _CRT_SECURE_NO_WARNINGS 1#include "Show.h"mytype n = 10;void show()
{printf("hello world\n");
}
Show.h文件中:
#pragma once//在.h文件中
//1.C头文件
//2.所有变量声明
//3.所有函数声明
//4.#define,类型typedef,struct#include typedef int mytype;extern mytype n;//变量声明一定要加externvoid show();typedef struct A
{mytype a;
}A;
最后打印出的结果:
输出:
输出:
10
10
hello world
这是对于分装.c文件和.h文件的一些补充知识和和说明。
我们在show.c文件中:
#define _CRT_SECURE_NO_WARNINGS 1#include "Show.h"//static修饰全局变量时,
//该变量只在别文件内被访问,不能被外部文件访问
static mytype n = 10;void show()
{printf("hello world\n");
}
然后编译就错误,无法通过了。
当然,static 也可以修饰函数。
#define _CRT_SECURE_NO_WARNINGS 1#include "Show.h"//static修饰全局变量时,
//该变量只在别文件内被访问,不能被外部文件访问
static mytype n = 10;//同理
static void show()
{printf("hello world\n");
}
这样,我们可以利用static保护我们的项目。
例:
这段代码因为 i 每次进入函数时都会重定义成1。
#include "Show.h"void f()
{int i = 0;i++;printf("%d ", i);}void print()
{for (int i = 0; i < 10; i++){f();}
}int main()
{print();return 0;
}
输出:
输出:1 1 1 1 1 1 1 1 1 1
而用 static 修饰:
#include "Show.h"void f()
{static int i = 0;i++;printf("%d ", i);}void print()
{for (int i = 0; i < 10; i++){f();}
}int main()
{print();return 0;
}
输出:
输出:1 2 3 4 5 6 7 8 9 10
总结:
static 修饰局部变量,更改局部变量的生命周期。
临时变量变成全局生命,但是作用域不变。
如下图:
局部变量被放到了全局数据区,或者说静态区。
(注:在整个进程运行生命周期内,都是有效的)
而在栈区的局部变量具有临时性。
以上就是本篇文章的内容了,感谢你的阅读。
如果喜欢本文的话,欢迎点赞和评论,写下你的见解。
如果想和我一起学习编程,不妨点个关注,我们一起学习,一同成长。
之后我还会输出更多高质量内容,欢迎收看。