Richard Taylor
Richard Taylor

Reputation: 2752

Extern Struct in C++?

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.

Upvotes: 23

Views: 57584

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 882751

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;
}

Upvotes: 35

user195488
user195488

Reputation:

You need to first define your struct in a class or common header file. Make sure you include this initial definition by means of #include "Class1.h" for instance.

Then, you need to modify your statement to say extern struct MyStruct theVar;

This statement does not need to be in a header file. It can be global.

Edit: Some .CPP file needs to contain the original declaration. All extern does is tell the compiler/linker to trust you that it exists somewhere else and when the program is built, it will find the valid definition. If you don't define struct MyStruct theVar somewhere, it likely won't compile all the way anyways when it reaches the linker.

Upvotes: 0

Related Questions