在 C++ 程序中制作全局结构
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2500677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making Global Struct in C++ Program
提问by mosg
I am trying to make globalstructure, which will be seen from any part of the source code. I need it for my big Qt project, where some global variables needed. Here it is: 3 files (global.h, dialog.h & main.cpp). For compilation I use Visual Studio (Visual C++).
我正在尝试制作全局结构,从源代码的任何部分都可以看到。我的大型 Qt 项目需要它,其中需要一些全局变量。这是:3 个文件(global.h、dialog.h 和 main.cpp)。对于编译,我使用 Visual Studio (Visual C++)。
global.h
全局文件
#ifndef GLOBAL_H_
#define GLOBAL_H_
typedef struct TNumber {
int g_nNumber;
} TNum;
TNum Num;
#endif
dialog.h
对话框.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
1>dialog.obj : error LNK2005: "struct TNumber Num" (?Num@@3UTNumber@@A) already defined in main.obj
Is there exists any solution?
有没有解决办法?
Thanks.
谢谢。
回答by Fred Larson
Yes. First, Don't define num
in the header file. 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.
是的。首先,不要num
在头文件中定义。将其声明为extern
标题,然后创建一个文件Global.cpp
来存储全局,或者main.cpp
按照 Thomas Jones-Low 的回答建议将其放入。
Second, don't use globals.
其次,不要使用全局变量。
Third, typedef
is unnecessary for this purpose in C++. You can declare your struct like this:
第三,typedef
在 C++ 中没有必要为此目的。你可以像这样声明你的结构:
struct TNum {
int g_nNumber;
};
回答by Thomas Jones-Low
In global.h
在 global.h
extern TNum Num;
then at the top of main.cpp
然后在 main.cpp 的顶部
TNum Num;
回答by quamrana
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 是不必要的。