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关键词的作用是扩大了变量的作用范围,表示在程序快内部可以使用程序快外部的变量。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!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