标签:int namespace C++ test extern using include 浅析
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而报错。
标签:int,namespace,C++,test,extern,using,include,浅析 来源: https://www.cnblogs.com/HikOldGhost/p/15975132.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。