我们真的可以使用 Static 来限制全局变量的范围吗?
我在某处读到我们只能通过以下方式将全局变量的范围限制为文件 在变量名前使用 static 关键字。但是,当我实际尝试时,结果是错误的:
//1st file - file1.c //2nd file - file2.h
#include<file2.h> static int a;
main()
{
fun();
}
fun()
{
printf("%d",a);
}
O/P is 0
现在我们确实有一个在 file2.h 中声明的全局变量 a ,其范围仅限于该文件.
因为我们已将其声明为静态,但我们仍然可以在 file1.c 中访问该变量。如何 ??
I have read somewhere that we can restrict the scope of global variable to a file only by
using static keyword before variable name. But, when i tried it practically it comes out to be false:
//1st file - file1.c //2nd file - file2.h
#include<file2.h> static int a;
main()
{
fun();
}
fun()
{
printf("%d",a);
}
O/P is 0
Now we do have a global variable a which is declared in file2.h, whose scope is limited to this file only.
Since, we have declared it as static, but still we can access this variable in file1.c. How ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在将全局变量的范围限制为文件语句中,文件表示编译单元,即
.c
文件。 file2.h 包含在 file1.c 中,它们构成一个编译单元file1
。将变量移至第二个编译单元,例如
file2.c
,您会发现即使使用extern
声明也无法访问它。In restrict the scope of global variable to a file statement, by file they mean compilation unit, i.e. a
.c
file. Your file2.h is included by file1.c and they constitute one compilation unitfile1
.Move the variable to a second compilation unit e.g.
file2.c
, and you'll see you can't access it even withextern
declaration.范围不限于文件,而是翻译单元。由于您将
file2.h
包含到file1.c
中,因此这就是一个 TU - 您不妨粘贴file2.h
的内容> 进入源文件。The scope is not restricted to a file, but to a translation unit. Since you include
file2.h
intofile1.c
, this is all one TU -- you might as well have pasted the content offile2.h
into the source file.您将文件
file2.h
包含在包含 main 的 c 文件中,在该文件中将变量声明为静态,这与在该 c 文件中编写声明一样好。当您包含声明静态变量的头文件时,将为包含该头文件的每个翻译单元(c 文件 + 包含的头文件)创建该变量的副本。
永远不要在头文件中声明静态变量。
要测试该场景,您应该这样做:
You are including the file
file2.h
in which you declared the variable as static in the c file which has main, which is as good as writing the declaration in that c file.When you include a header file which declares a static variable a copy of the variable gets created for each translation unit(c file + included header files) in which the header file is included.
Never declare your static variables in header file.
To test the scenario, You should do this:
范围是在 C 的预处理器运行后定义的。即:在所有 #include 语句都已被评估和内联之后。
Scope is defined after C's pre-processor has run. Ie: after all #include-statements have been evaluated and inlined.