extern定义全局变量的使用

1、extern的作用

extern关键字在C/C++中用来声明一个全局变量,指出这个全局变量在另一个文件中定义,也可以用来引用一个全局变量

假设我们有三个文件:commands.hmain.cpp,和other.cpp。我们在commands.h中声明了一个全局变量 flightCommand1,然后在main.cpp中定义并初始化这个变量,最后在other.cpp中使用这个变量。

commands.h

这是头文件,它包含了flightCommand1的声明。使用extern关键字声明变量,表示它的定义在别的地方。

1 #ifndef COMMANDS_H
2 #define COMMANDS_H
3 
4 #include <QList>
5 #include <QString>
6 
7 extern QList<QString> flightCommand1;
8 
9 #endif // COMMANDS_H

main.cpp

这是主程序文件,它包含了flightCommand1的定义和初始化。注意,在这里我们不使用extern关键字

 1 #include "commands.h"
 2 
 3 // 定义并初始化 flightCommand1
 4 QList<QString> flightCommand1 = {};
 5 
 6 int main() {
 7     // 这里可以填充 flightCommand1 或者执行其他操作
 8     flightCommand1.append("Command1");
 9     flightCommand1.append("Command2");
10 
11     return 0;
12 }

other.cpp

这是另一个程序文件,它展示了如何使用在commands.h中声明的全局变量flightCommand1。在这个文件中,我们只需要包含commands.h头文件。由于flightCommand1是用extern声明的,编译器知道去查找在别的文件中定义的该变量。

 1 #include "commands.h"
 2 #include <iostream>
 3 
 4 void printCommands() {
 5     for (const QString& cmd : flightCommand1) {
 6         std::cout << cmd.toStdString() << std::endl;
 7     }
 8 }
 9 
10 int main() {
11     printCommands();
12     return 0;
13 }

commands.h中使用extern关键字声明全局变量flightCommand1:这告诉编译器该变量在程序的其他地方(另一个文件)被定义。这样,任何包含了commands.h的文件都会知道flightCommand1的存在,但不会在这些文件中创建新的变量实例。

main.cpp中定义和初始化flightCommand1:这里是flightCommand1实际存储空间的创建位置。由于这个定义提供了变量的实际存储和初始值,因此不需要(也不能)使用extern关键字。

other.cpp(或任何其他包含commands.h的文件)中使用flightCommand1:由于commands.h已经通过extern声明了flightCommand1,因此当other.cpp包含了这个头文件时,它就能够使用这个全局变量。在这种情况下,不需要在other.cpp中再次使用extern来声明flightCommand1

 

posted @ 2024-03-28 13:45  taohuaxiaochunfeng  阅读(40)  评论(0编辑  收藏  举报