如何使用头文件在文件之间共享全局变量?

How to share a global variable between files using header file?

我有一个头文件和3个cpp文件。我想在我的文件之间共享一个数组对象以在其中存储数据并使用它(全局变量)。

我的头文件代码:info.h

#ifndef INFO_H
#define INFO_H
#include "QString"
class ib
{
public:
    QString from,to,seat[32],driver;
}extern o[10];
#endif // INFO_H

和我的 cpp 文件代码: bilit.cpp

#include "info.h"
void bilit::on_pushButton_clicked()
{
    const int f = ui->bnspin->value();
    const int s = ui->stspin->value();
    o[f].seat[s] = ui->pnbtn->text();
}

make.cpp

#include "info.h"
void make::on_pushButton_clicked()
{
    const int f = ui->spinBox->value();
    o[f].driver = ui->drvbtn->text();
    o[f].to = ui->tobtn->text();
    o[f].from = ui->frombtn->text();
}

check.cpp

#include "info.h"
void check::on_pushButton_clicked()
{
    const int f = ui->spinBox->value();
    const int s = ui->spinBox_2->value();
    ui->label->setText(o[f].seat[s]);
}

这是我的错误: error

即使我在我的 cpp 文件中写了 extern,但我再次出错: error2

知道如何解决吗?或其他方式在我的文件之间共享全局变量?

如果您使用 extern,您需要在您的某个 cpp 文件中的某处进行定义。查看 here 了解更多信息。

我想如果你这样改变你的文件:

#ifndef INFO_H
#define INFO_H
#include "QString"
class ib
{
public:
    QString from,to,seat[32],driver;
};

extern ib o[10];
#endif
#include "info.h"

ib o[10]; // <-- here we define object that will be extern-ed.

void bilit::on_pushButton_clicked()
{
    const int f = ui->bnspin->value();
    const int s = ui->stspin->value();
    o[f].seat[s] = ui->pnbtn->text();
}

它将解决问题。

可以多次将一个对象声明为extern。它的意思是“这个对象的链接数据在别的地方”。

您的代码不包含“其他地方”定义。

file.h:

extern int i; // i is defined somewhere else

file.cpp:

int i = 0; // this is the definition

其他人file.cpp:

extern int i; // will use the same i in file.cpp
              // alternatively, to avoid duplicating the extern declaration,
              // you can just include file.h

总而言之,在您的一个 cpp 文件中,您需要添加:

ib o[10];