简体   繁体   English

在C ++程序中实现全局结构

[英]Making Global Struct in C++ Program

I am trying to make global structure, which will be seen from any part of the source code. 我正在尝试创建全局结构,这将从源代码的任何部分看出。 I need it for my big Qt project, where some global variables needed. 我需要它用于我的大型Qt项目,需要一些全局变量。 Here it is: 3 files (global.h, dialog.h & main.cpp). 这是:3个文件(global.h,dialog.h和main.cpp)。 For compilation I use Visual Studio (Visual C++). 对于编译,我使用Visual Studio(Visual C ++)。

global.h global.h

#ifndef GLOBAL_H_
#define GLOBAL_H_

typedef struct  TNumber {
    int g_nNumber;
} TNum;

TNum Num;

#endif

dialog.h dialog.h

#ifndef DIALOG_H_
#define DIALOG_H_

#include <iostream>
#include "global.h"

using namespace std;

class   ClassB {
public:
    ClassB() {};

    void    showNumber() {
        Num.g_nNumber = 82;
        cout << "[ClassB][Change Number]: " << Num.g_nNumber << endl;
    }
};

#endif

and main.cpp main.cpp

#include <iostream>

#include "global.h"
#include "dialog.h"

using namespace std;

class   ClassA {
public:
    ClassA() {
        cout << "Hello from class A!\n";
    };
    void    showNumber() {
        cout << "[ClassA]: " << Num.g_nNumber << endl;
    }
};

int main(int argc, char **argv) {
    ClassA  ca;
    ClassB  cb;
    ca.showNumber();
    cb.showNumber();
    ca.showNumber();
    cout << "Exit.\n";
    return 0;
}

When I`m trying to build this little application, compilation works fine, but the linker gives me back an error: 当我试图构建这个小应用程序时,编译工作正常,但链接器给我一个错误:

1>dialog.obj : error LNK2005: "struct TNumber Num" (?Num@@3UTNumber@@A) already defined in main.obj

Is there exists any solution? 有没有解决方案?

Thanks. 谢谢。

Yes. 是。 First, Don't define num in the header file. 首先,不要在头文件中定义num Declare it as extern in the header and then create a file Global.cpp to store the global, or put it in main.cpp as Thomas Jones-Low's answer suggested. 在标题中将其声明为extern ,然后创建一个文件Global.cpp来存储全局,或者将其放在main.cpp如Thomas Jones-Low的回答所示。

Second, don't use globals. 其次,不要使用全局变量。

Third, typedef is unnecessary for this purpose in C++. 第三,在C ++中为此目的不需要typedef You can declare your struct like this: 您可以像这样声明您的结构:

struct  TNum {
    int g_nNumber;
};

In global.h 在global.h中

extern TNum Num;

then at the top of main.cpp 然后在main.cpp的顶部

TNum Num;

Since you're writing in C++ use this form of declaration for a struct: 因为你是用C ++编写的,所以使用这种形式的结构声明:

struct  TNumber {
    int g_nNumber;
};

extern TNumber Num;

The typedef is unnecessary. typedef是不必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM