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浅析的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程