C语言中的外部和全局 [英] extern and global in c
问题描述
谁能告诉我在C程序中使用 EXTERN
或 GLOBAL
变量是否有特殊要求?如果我从gloabl更改为extern,则在下面的程序中看不到任何区别.
Can anyone please tell me is there any special requirement to use either EXTERN
or GLOBAL
variables in a C program?
I do not see any difference in a program like below, if I change from gloabl to extern.
#include <stdio.h>
#include <stdlib.h>
int myGlobalvar = 10;
int main(int argc, char *argv[])
{
int myFunc(int);
int i;
i = 12;
myGlobalvar = 100;
printf("Value of myGlobalvar is %d , i = %d\n", myGlobalvar, i);
i = myFunc(10);
printf("Value of passed value : %d\n",i);
printf("again Value of myGlobalvar is %d , i = %d\n", myGlobalvar, i);
system("PAUSE");
return 0;
}
int myFunc(int i)
{
i = 20 + 1000;
//extern int myGlobalvar;
myGlobalvar = 20000;
// printf("Value of passed value : %d",i);
return i;
}
如果取消注释 extern int myGlobalvar
,则该值不会更改.
If uncomment extern int myGlobalvar
, the value does not change.
两者之间是否存在正确
差异?
Is there any correct
difference between both?
有人可以纠正我吗?
推荐答案
关键字 extern
表示此变量的存储已分配到其他位置".它告诉编译器我在这里引用 myGlobalvar
,并且您之前从未见过,但这没关系;链接器将知道您在说什么."在您的特定示例中,它并不是特别有用,因为编译器确实知道 myGlobalvar
-它是在同一个翻译单元( .c
或 .cc
文件.)当您要引用当前翻译单元中不是的内容时,通常使用 extern
.您将要链接到的库中定义的变量.
The keyword extern
means "the storage for this variable is allocated elsewhere". It tells the compiler "I'm referencing myGlobalvar
here, and you haven't seen it before, but that's OK; the linker will know what you are talking about." In your specific example it's not particularly useful, because the compiler does know about myGlobalvar
-- it's defined earlier in the same translation unit (.c
or .cc
file.) You normally use extern
when you want to refer to something that is not in the current translation unit, such as a variable that's defined in a library you will be linking to.
(当然,通常该库会在您应包括的头文件中为您声明 extern
变量.)
(Of course, normally that library would declare the extern
variables for you, in a header file that you should include.)
这篇关于C语言中的外部和全局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!