C++ extern浅析
2022/3/7 12:16:33
本文主要是介绍C++ extern浅析,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
extern是外部声明关键字,字面意思就是声明某种变量或函数,在外部定义。
extern声明变量的两种方法
1.在其他文件中直接extern
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 extern int a ; 5 6 int main() { 7 cout << a << endl; 8 return 0; 9 }
1 #include<iostream> 2 #include"test.h" 3 using namespace std; 4 int a = 0;
2.在源文件中定义,头文件中使用extern声明,然后使用其他文件直接包含头文件
1 #include<iostream> 2 #include<vector> 3 #include"test.h" 4 using namespace std; 5 6 int main() { 7 cout << a << endl; 8 return 0; 9 }
1 /* test.h */ 2 3 #ifndef_TEST_H_ 4 #define_TEST_H_ 5 6 extern int a; 7 8 #endif
1 #include<iostream> 2 #include"test.h" 3 using namespace std; 4 int a = 0;
注意:以下是错误示范,编译器会报错显示变量a被重定义
1 #include<iostream> 2 #include<vector> 3 #include"test.h" 4 using namespace std; 5 6 int main() { 7 cout << a << endl; 8 return 0; 9 } 10 点击并拖拽以移动 11 /* test.h */ 12 13 #ifndef_TEST_H_ 14 #define_TEST_H_ 15 16 int a;//头文件中定义变量,源文件中使用变量 17 18 #endif
1 /* test.h */ 2 #ifndef_TEST_H_ 3 #define_TEST_H_ 4 5 int a;//头文件中定义变量,源文件中使用变量 6 #endif
1 #include<iostream> 2 #include"test.h" 3 using namespace std; 4 a = 0;
有两个源文件包含了头文件,编译阶段会因为两次定义变量a而报错。
这篇关于C++ extern浅析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升