问题描述
我正在尝试构建全局结构,该结构可以从源代码的任何部分看到.对于我的大型Qt项目,需要一些全局变量,我需要它.它是:3个文件(global.h,dialog.h和main.cpp).对于编译,我使用Visual Studio(Visual C ++).
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. Here it is: 3 files (global.h, dialog.h & main.cpp). For compilation I use Visual Studio (Visual C++).
global.h
#ifndef GLOBAL_H_
#define GLOBAL_H_
typedef struct TNumber {
int g_nNumber;
} TNum;
TNum Num;
#endif
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
和 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
有解决方案吗?
谢谢.
推荐答案
是.首先,不要在头文件中定义num
.在标题中将其声明为extern
,然后创建文件Global.cpp
来存储全局文件,或者按照Thomas Jones-Low的回答建议将其放在main.cpp
中.
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.
第二,不要使用全局变量.
Second, don't use globals.
第三,在C ++中,为此不需要typedef
.您可以这样声明您的结构:
Third, typedef
is unnecessary for this purpose in C++. You can declare your struct like this:
struct TNum {
int g_nNumber;
};
这篇关于在C ++程序中进行全局构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!