tags:

views:

235

answers:

3

Hello world!

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.

+2  A: 

In global.h

extern TNum Num;

then at the top of main.cpp

TNum Num;
Thomas Jones-Low
+5  A: 

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;
};
Fred Larson
+1  A: 

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.

quamrana