2013年4月8日 星期一

extern struct

http://stackoverflow.com/questions/3266580/extern-struct

I'm using extern to fetch variables from another class, and it works fine for int's, float's etc...
But this doesn't work, and I don't know how to do it:

Class1.cpp
struct MyStruct {
 int x;
}

MyStruct theVar;
 
Class2.cpp
extern MyStruct theVar;

void test() {
 int t = theVar.x;
}
 
It doesn't work because Class2 doesn't know what MyStruct is.
How do I fix this? :/
I tried declaring the same struct in Class2.cpp, and it compiled, but the values were wrong.


7 down vote accepted
You put the struct MyStruct type declaration in a .h file and include it in both class1.cpp and class2.cpp.
IOW:
Myst.h
struct MyStruct {
 int x;
};
 
Class1.cpp
#include "Myst.h"

MyStruct theVar;
 
Class2.cpp
#include "Myst.h"

extern struct MyStruct theVar;

void test() {
 int t = theVar.x;
}

沒有留言:

張貼留言