了解C语言中的`extern`存储类说明符 [英] Understanding `extern` storage class specifier in C

查看:131
本文介绍了了解C语言中的`extern`存储类说明符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑给定的C代码:

#include<stdio.h>
extern int i;
int main(){
    printf("%d", i);
    return 0;
}

它给出Compilation error.如果我初始化extern int i=10;,则输出为10.

It gives Compilation error. While if I initialize extern int i=10; then output is 10.

#include<stdio.h>
extern int i=10; //initialization statement
int main(){
    printf("%d", i);
    return 0;
}

而且,如果我分配int i=10;,则输出为10.

And also, if I assign int i=10;then output is 10.

#include<stdio.h>
 extern int i;
 int i=10;  //assignment
int main(){
    printf("%d", i);
    return 0;
}

还有

#include<stdio.h>
 extern int i;
 int main(){
    int i=10;   //assignment
    printf("%d", i);
    return 0;
}


变化:


Variation :

#include<stdio.h>
 extern int i;
 int i=20;
 int main(){
    int i=10;
    printf("%d", i);
    return 0;
}

由于int i是局部变量,所以输出为10.

Since, int i is local variable, so output is 10.

请,您能解释一下有关C语言中extern存储类的一些重要观点吗?

Please, can you explain some important point about extern storage class in C


我在某处阅读,声明声明了变量或函数的名称和类型.定义导致为要定义的变量或函数主体分配存储空间.同一变量或函数可能有许多声明,但该变量或函数只能有一个定义.


I read somewhere, a declaration declares the name and type of variable or function. A definition causes storage to be allocated for the variable or the body of the function to be defined. The same variable or function may have many declaration, but there can be only one defition for that variable or function.

推荐答案

考虑

int i;

在程序的所有功能(包括main)之外声明.

declared outside all the functions of the programme including main.

这意味着i将拥有

  • 文件范围
  • 静态存储期限
  • 为i分配了空间. #这很重要.

考虑

extern int i;

在程序的所有功能(包括main.
)之外声明. 这意味着i将拥有

declared outside all the functions of the programme including main.
This means i will have

  • 文件范围
  • 静态存储期限
  • i仅声明,未定义,这意味着未分配空间.
  • 假定
  • i是在其他地方定义的,可能在包含文件中
  • file scope
  • static storage duration
  • i is only declared, not defined which means space is not allocated.
  • i is assumed to be defined somewhere else, may be, in an include file

考虑

extern int i=10; 

在程序的所有功能(包括main)中声明.
在初始化extern变量i的情况下.在这种情况下

declared outside all the functions of the programme including main.
This is the case where you're initializing the extern variable i. In this case

  • i分配了空间.
  • 我将被初始化为10.
  • 忽略了关键字extern,这意味着i不是declared only.
  • Space is allocated for i.
  • i will be initialized to 10.
  • The keyword extern is neglected which means i is NOT declared only.

注意

对于extern int i,必须在其他位置(即在另一个源文件中)定义变量.如果不是这种情况,则会出现编译时错误.

For extern int i it is mandatory that the variable should be defined somewhere else, ie in another source file. If this is not the case, you will a compile-time error.

这篇关于了解C语言中的`extern`存储类说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆