I’m having some trouble compiling/linking a set of classes, several of them dealing with a common global variable.
Basically, I declare and define a extern variable foo in class A and access/update it in classes B and C.
The relevant code looks like this:
A.h
extern string foo; // declare it <=== compiler error "storage class specified for foo"
B.cpp
include A.h
string foo; // define it
main () {
...
foo = "abc";
}
C.cpp
include A.h
cout << foo; // print it
My current error is “storage class specified for foo”. But, I’m wondering if this is the correct approach. Should I be using a static variable? Any help much appreciated, as I’ve been on this for at least an hour by now.
In A.h have you actually got the extern declaration within the actual class A? Your question currently says this in words but then your code snippet suggests it is at file level. The only way I can get the error you are talking about i.e. “storage class specified for foo” is for the following in A.h:
Perhaps this is your problem?
Edit: Looking at your own answer I think this is what you’ve done. You want to replace
externwithstaticand then define that static in A.cpp with a line likeYou can then subsequently access it in other places as
A::fooeg.