Making Global Struct in C++ Program
Solution 1
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.
Third, typedef
is unnecessary for this purpose in C++. You can declare your struct like this:
struct TNum {
int g_nNumber;
};
Solution 2
In global.h
extern TNum Num;
then at the top of main.cpp
TNum Num;
Solution 3
Since you're writing in C++ use this form of declaration for a struct:
struct TNumber {
int g_nNumber;
};
extern TNumber Num;
The typedef is unnecessary.
Comments
-
mosg almost 4 years
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
and 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.
-
William FitzPatrick almost 6 yearsThis answer would be much more useful if an alternative for globals were offered
-
Barleyman about 4 years@WilliamFitzPatrick Globals have their place, especially static globals which are only visible inside the specific source file. Maybe your program simply isn't million lines with hundreds of people working on it? Maybe passing that configuration object from one function to the other all over the code doesn't make sense? Maybe you just stick your configuration into one static global struct so all of your local-to-that-file functions can access the configuration which is only even written by one parsing function but read in several places.