PDA

View Full Version : Declare global array of a struct in another header file



persianpatient
14th September 2015, 16:17
Hi ,

I have a structure that defines something for example personal information , I have this struct in my Globals.h file , something like this :


struct Persons{
QString Name;
QString Email;
int Age;
QString Gender;
};


in Globals.cpp , I defined an array of this struct like this :


extern Persons myPers[100];


now , I have to use this array everywhere of my application , in different Threads , but I can not , I am new in c++ and QT , but I have basic knowledge of c++ programming , is my array definition correct ? is my structure definition correct , what is the safe and right way to use this array ?

Best Regards,
Amir .

yeye_olive
14th September 2015, 16:56
This is a general C++ question; it is not specific to Qt.

Your definition of struct Persons look correct.

The line

extern Persons myPers[100];
is not a definition, but a declaration. Along with the definition of struct Persons, it should appear in each source file (i.e. .cpp file) that needs to access the myPers array. It tells the compiler everything it needs to know about the array in order to use it, without actually allocating and initializing it. Instead of copying this line in every source file, people usually put it in a .h that they then #include in the .cpp file. You did just that with struct Persons by defining it in Globals.h; you could simply move the declaration of the array there.

Now, after the compiler has compiled all your .cpp files, it will try to link them together to form an autonomous executable. The linker will complain because no one has allocated the myPers array. You should therefore define the array somewhere in a .cpp file (and only there). The definition looks just like the declaration, but without extern:

Persons myPers[100];
(Note: this definition default-initializes the array; there are other ways to initialize the array, but this is beyond the scope of this post.)

Although all of this is correct, this is C-style programming (structures, plain arrays and global variables), as opposed to C++-style (classes and containers).

Finally, you mentioned threads in your post. Different threads can access different objects concurrently, but they must synchronize whenever one of them writes to an object when another thread might be reading from the same object. You can prevent several threads from accessing the same object at a given time by protecting all accesses with a mutex (see QMutex, for instance). Depending on the amount of concurrency you want to allow, you could have a global mutex for the whole array, or a mutex for each element, etc.

persianpatient
14th September 2015, 17:28
Dear yeye_olive,

Thank you very much for your explanation .
now I'm trying to use QMutex in my application .

Best Regards,
Amir .