Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extern Struct in C++?

Tags:

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.

like image 335
Richard Taylor Avatar asked Jul 16 '10 15:07

Richard Taylor


People also ask

What is the use of extern in C?

extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention. The extern "C" modifier may also be applied to multiple function declarations in a block. In a template declaration, extern specifies that the template has already been instantiated elsewhere.

What is extern variable in C?

CProgrammingServer Side Programming. External variables are also known as global variables. These variables are defined outside the function. These variables are available globally throughout the function execution.

How do you use struct in another file?

The easy solution is to put the definition in an header file, and then include it in all the source file that use the structure. To access the same instance of the struct across the source files, you can still use the extern method.

What is Typedef structure in C?

The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g.,​ int) and user-defined​ (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.


1 Answers

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;
}
like image 62
Alex Martelli Avatar answered Nov 06 '22 20:11

Alex Martelli