Extern可以使函数变量成为全局变量吗?
如我所知,extern
使变量 - >全局变量,因此这意味着我们还可以使另一个函数的变量成为全局变量?
#include <stdio.h>
extern char* name;
void namePrint();
int main(void) {
printf("%s\n", name);
namePrint();
}
void namePrint() {
printf("%s", name);
char* name = "Satyam";
}
As I understood extern
makes a variable --> global variable, so it means we can also make variable of another function a global variable?
#include <stdio.h>
extern char* name;
void namePrint();
int main(void) {
printf("%s\n", name);
namePrint();
}
void namePrint() {
printf("%s", name);
char* name = "Satyam";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您了解外部错误。这不是要制作符号“全局”。告诉编译器,关于在其他地方创建的符号的存在(实际上是“ extern”含义)中的存在。
在使用之前,它是一种声明功能。在功能声明中使用
extern
是允许的:实际上,在语义上声明了通常的函数,即不使用
extern
只是 shorthand 做。You understood extern wrong. It's not about making symbols "global". Tells tells the compiler about the existence of a symbol that has been created somewhere else, that is outside (which is literally what the word "extern" means) from the current translation unit.
It's kind of declaring a function before using it. Using
extern
in function declarations is allowed:In fact semantically the usual functions are declared, that is without the use of
extern
is just a shorthand for doing it with.通过术语“全局变量” C程序员表示具有文件范围的变量(具有外部或内部链接)。
函数中声明的变量是局部变量,在声明其声明的功能范围之外不可见。
您可以在函数中声明一个变量,该变量将使用存储类规范仪外部指出文件范围中的变量。例如
,在函数
namepring
声明的变量名称
中,请参考文件范围中声明的全局变量 name 。也就是说,它表示全局变量名称
。或更有意义的例子
By the term "global variable" C programmers mean variables (with external or internal linkage) having file scope.
Variables declared within functions are local variables and invisible outside the function scope where they are declared.
You could declare within a function a variable that will refer to a variable in file scope using the storage class specifier extern. For example
Here within the function
namePring
the declared variablename
refers to the global variablename
declared in the file scope. That is it denotes the global variablename
.Or more meaningful example
除其他答案外:
由于您的代码现在,它会编译,但没有链接。
通过
extern char* name;
您告诉编译器某处 全局变量name
存在。编译器对此很好。此功能:
在
printf()
调用中使用此全局变量。以下行中本地变量的本地变量的定义是另一个具有相同名称的变量。如果有一些代码访问name
之后(不是),它将“阴影”全局变量。因为您从未定义全局变量
name
,所以链接器无法解析引用。In addition to the other answers:
As your code is now, it compiles, but doesn't link.
By
extern char* name;
you are telling the compiler that somewhere a global variablename
exists. The compiler is fine with this.This function:
uses this global variable in the
printf()
call. The definition of the local variablename
in the following line is another variable with the same name. It would "shadow" the global variable, if there were some code accessingname
afterwards (it isn't).Because you never define the global variable
name
, the linker cannot resolve the references.