作用域和链接属性

一、作用域:

        当变量被定义在程序的不脱那个位置时,它的作用范围是不一样的,这个作用范围就是我们所说的作用域。

C语言编译器可以确认4种不同类型的作用域:

        1.代码块作用域

#include<stdio.h>
int main()
{
        int i=100;//i1
        {
                printf("i2=%d\n",i);
                int i=111;//i2
                {
                        int i=333;//i3
                        printf("i3=%d\n",i);
                }
                //出到了这里,i变回了111
                {
                        printf("i4=%d\n",i);
                        int i=666;//i4
                        printf("i4=%d\n",i);
                }
                printf("i2=%d\n",i);
        }
        printf("i1=%d\n",i);
        return 0;
}

运行结果:

lhy@ubuntu:~/xiaojiayu$ gcc p32-1.c 
lhy@ubuntu:~/xiaojiayu$ ./a.out 
i2=100
i3=333
i4=111
i4=666
i2=111
i1=100

        2.文件作用域

#include<stdio.h>

void func();

int main()
{
        extern int count;

        func();
        count++;
        printf("In main,count=%d\n",count);
        return 0;
}
int count;

void func()
{
        count++;
        printf("In func,count=%d\n",count);
}

运行结果:

lhy@ubuntu:~/xiaojiayu$ gcc p32-2.c 
lhy@ubuntu:~/xiaojiayu$ ./a.out 
In func,count=1
In main,count=2

        3.原型作用域

        4.函数作用域

二、链接属性

 

​#include<stdio.h>
void a();
void b();
void c();
int count;
int main()
{
        a();
        b();
        c();
        b();
        printf("count=%d\n",count);
        return 0;
}

​
extern int count;
void a()
{
        count++;
}
extern int count;
void b()
{
        count++;
}
extern int count;
void c()
{
        count++;
}

运行结果:

lhy@ubuntu:~/xiaojiayu$ gcc p32-3.c a.c b.c c.c 
lhy@ubuntu:~/xiaojiayu$ ./a.out 
count=4

#include<stdio.h>
void a();
void b();
void c();
static count;
int main()
{
        a();
        b();
        c();
        b();
        printf("count=%d\n",count);
        return 0;
}
extern int count;
void c()
{
        count++;
}

运行结果:

lhy@ubuntu:~/xiaojiayu$ gcc p32-3.c a.c b.c c.c 
p32-3.c:5:8: warning: type defaults to ‘int’ in declaration of ‘count’ [-Wimplicit-int]
 static count;
        ^~~~~
/tmp/cck8WWlb.o: In function `a':
a.c:(.text+0x6): undefined reference to `count'
a.c:(.text+0xf): undefined reference to `count'
/tmp/ccbT0cJ9.o: In function `b':
b.c:(.text+0x6): undefined reference to `count'
b.c:(.text+0xf): undefined reference to `count'
/tmp/cc01llk8.o: In function `c':
c.c:(.text+0x6): undefined reference to `count'
/tmp/cc01llk8.o:c.c:(.text+0xf): more undefined references to `count' follow
collect2: error: ld returned 1 exit status

另:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值