I would like to share a C++ struct between two files (in context of Android-NDK programming). In the first one the struct is initialized and in the other one it is finally used.
So I define the struct in a header file struct.h (which I include in both .cpp files) and declare it as a static variable:
struct A {
int v;
A(){
v = 0;
}
}
static A structA;
Then I assign a value to it in the first i.cpp-File e.g.: A.v = 5. But when I call it in the second one j.cpp it`s still 0.
The whole process looks like this:
Java Code -> call i.cpp and assign value -> Java Code -> call j.cpp and read value -> wrong
but
Java Code -> call i.cpp and assign value -> Java Code -> call i.cpp and read value -> correct
First, what you want to share is an object, not a struct. The struct defines the type of the object.
Second,
staticmeans “don’t share this with other translation units”. I’ll bet you stuck that in there because without it you got a complaint from the linker about duplicate definitions.The way to do that is to declare the object in the header and define it in only one place. This goes in the header:
And this goes in the source file where you want to initialize it: