Making Global Struct in C++ Program

泪湿孤枕 提交于 2019-12-10 19:33:18

问题


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.


回答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;
};



回答2:


In global.h

extern TNum Num;

then at the top of main.cpp

TNum Num;



回答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.



来源:https://stackoverflow.com/questions/2500677/making-global-struct-in-c-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!