Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to same structure instance from another .c file

How to access the same instance of structure defined in first.c from second.c file

What is the most appropriate way?

We put something like this in first.h file:

typedef struct
{ 
    int a;
    double b;
} myStruct;

This code above represents definition of new type myStruct, and also a declaration as it says compiler that structure like this exist somewhere?

In first.c file we should add:

myStruct tmpStructure;// here we make instance of the myStruct type and allocate memory space for it, which is called definition?

And in second.c if we want to use the same instance of this myStruct type, we should put:

extern myStruct tmpStruct; //which will say our compiler there is a definition of this type in some other file than this second.c, go search outside for it.

Does all of this function like 'explained'?

like image 620
EmbeddedMan Avatar asked Jul 10 '26 00:07

EmbeddedMan


1 Answers

What you have guessed is at all correct. One common approach you have not mentioned is that you can also put in the header file the following:

extern myStruct tmpStruct;

It does not hurt in the file in which you define the variable and informs the compiler(declares) of an external variable of such type defined elsewhere in the program. So if you header file finally reads:

typedef struct
{ 
    int a;
    double b;
} myStruct;

extern myStruct tmpStruct;

you can use tmpStruct in both files without any further declaration (of course you need still to do the actual definition in first.c. Also, you have an extra security check in case you change the type of tmpStruct, as you'll get an error in case you change it in the definition file and not in the header or viceversa.

like image 121
Luis Colorado Avatar answered Jul 11 '26 14:07

Luis Colorado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!