c语言中extern关键字

 

最简单的例子:

001、 不适用extern关键字声明变量

复制代码
[root@PC1 test]# ls
test.c
[root@PC1 test]# cat test.c                ##   测试c程序 
#include <stdio.h>


int main(void)
{

        printf("x = %d\n", x);            // 调用变量x

        return 0;
}


int x = 10;                               // 变量x在程序块外定义
[root@PC1 test]# gcc test.c -o kkk        ## 变异报错
test.c: In function ‘main’:
test.c:7:21: error: ‘x’ undeclared (first use in this function)
  printf("x = %d\n", x);
                     ^
test.c:7:21: note: each undeclared identifier is reported only once for each function it appears in
复制代码

。 

 

002、使用extern关键字

复制代码
[root@PC1 test]# ls
test.c
[root@PC1 test]# cat test.c
#include <stdio.h>


int main(void)
{

        extern x;                //  此处使用extern关键词,表示使用外部变量x
        printf("x = %d\n", x);

        return 0;
}


int x = 10;
[root@PC1 test]# gcc test.c -o kkk        ## 编译、执行都没有问题
[root@PC1 test]# ls
kkk  test.c
[root@PC1 test]# ./kkk
x = 10
复制代码

 。

 

extern关键词的作用是扩大了变量的作用范围,表示在程序快内部可以使用程序快外部的变量。

 

posted @   小鲨鱼2018  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2023-11-12 Linux 中设置打开文件数目限制的方法
2023-11-12 Linux 中 source 命令
2023-11-12 Linux 中 export 命令 对变量发挥什么作用 ?
2022-11-12 python 中统计fasta文件中每条scaffold中碱基的数目
2022-11-12 linux 中shell 脚本将 gff文件转换为bed文件
2020-11-12 ansible
点击右上角即可分享
微信分享提示