If you are trying to share a structure definition between several compilation units (cpp files), the general way is this: put the definition of your structure in the header file (mystruct.h). If the structure contains any methods (i.e., by default it is a class with all public members), you can implement them in the mystruct.CPP file or, if they are lightweight, directly inside the structure (which makes them inline by default).
mystruct.h:
#ifndef MYSTRUCT_H #define MYSTRUCT_H struct MyStruct { int x; void f1() { } void f2(); }; #endif
mystruct.cpp
#include "mystruct.h"
You can use your structure in as many cpp files as you like, just #include mystruct.h:
main.cpp
#include "mystruct.h" int main() { MyStruct myStruct; myStruct.x = 1; myStruct.f2();
If, on the other hand, you are trying to pass a global instance of the structure through several compilation units (this is not entirely clear from your question), do as described above, and also add
extern MyStruct globalStruct;
to mystruct.h. This will indicate that the instance is available with external communication; in other words, that the variable exists, but is initialized elsewhere (in your case in mystruct.cpp). Add global instance initialization to mystruct.cpp:
MyStruct globalStruct;
It is important. Without manually creating an instance of globalStruct you will get unresolved-external . You now have access to globalStruct from each compilation module, which includes mystruct.h.
Martin gunia
source share