1.如何引用一个已经定义过的全局变量?
答:extern 可以用引用头文件的方式,也可以用extern关键字,如果用引用头文件方式来引用某个在头文件中声明的全局变理,假定你将那个编写错了,那么在编译期间会报错,如果你用extern方式引用时,假定你犯了同样的错误,那么在编译期间不会报错,而在连接期间报错。
2.全局变量可不可以定义在可被多个.C文件包含的头文件中?为什么?
答:可以,在不同的C文件中以static形式来声明同名全局变量。 可以在不同的C文件中声明同名的全局变量,前提是其中只能有一个C文件中对此变量赋初值,此时连接不会出错
3.通过下例要看出static全局变量与普通的全局变量有什么区别来?
全局变量(外部变量)的说明之前再冠以static 就构成了静态的全局变量。全局变量本身就是静态存储方式, 静态全局变量当然也是静态存储方式。 这两者在存储方式上并无不同。这两者的区别在于非静态全局变量的作用域是整个源程序, 当一个源程序由多个源文件组成时,非静态的全局变量在各个源文件中都是有效的。 而静态全局变量则限制了其作用域, 即只在定义该变量的源文件内有效, 在同一源程序的其它源文件中不能使用它。由于静态全局变量的作用域局限于一个源文件内,只能为该源文件内的函数公用, 因此可以避免在其它源文件中引起错误
fu1.h:
- #ifndef FF1_h
- #define FF1_h
- #include<stdio.h>
- void setone();
- #endif
fu1.c:
- #include"fu1.h"
- int i;
- void setone()
- {
- printf("%d/n", i);
- }
fu2.h
- #ifndef FF2_h
- #define FF2_h
- #include<stdio.h>
- void settwo();
- #endif
fu2.c
- #include"fu2.h"
- int i;
- void settwo()
- {
- printf("%d/n", i);
- }
test.c
- #include"fu1.h"
- #include"fu2.h"
- int i=36;
- int main(void)
- {
- printf("%d/n", i);
- i =3;
- setone();
- i = 6;
- settwo();
- }
运行结果:
36
3
6
fu1.h
- #ifndef FF1_h
- #define FF1_h
- #include<stdio.h>
- void setone();
- #endif
fu1.c
- #include"fu1.h"
- int i= 86;
- void setone()
- {
- printf("%d/n", i);
- }
test.c
- #include<stdio.h>
- extern int i;
- int main(void)
- {
- printf("%d/n", i);
- i =3;
- printf("%d/n", i);
- setone();
- }
运行结果:
86
3
3
fu1.h
- #ifndef FF1_h
- #define FF1_h
- #include<stdio.h>
- #include<stdlib.h>
- void setone();
- #endif
fu1.c
- #include"fu1.h"
- static int i;
- void setone()
- {
- printf("%d/n", i);
- }
fu2.h
- #ifndef FF2_h
- #define FF2_h
- #include<stdio.h>
- #include<stdlib.h>
- void settwo();
- #endif
fu2.c
- #include"fu2.h"
- static int i;
- void settwo()
- {
- printf("%d/n", i);
- }
test.c
- #include"fu1.h"
- #include"fu2.h"
- static int i = 40;
- int main(void)
- {
- printf("%d/n", i);
- i =3;
- printf("%d/n", i);
- setone();
- i = 6;
- settwo();
- }
运行结果:
40
3
0
0