How can I use a global structure pointer in ansi-c?

Like this. In the fileA.c file I have

typedef struct MY_STRUCT { int A; int B; int C; }MY_STRUCT; MY_STRUCT Data; /* Function */ int function(MY_STRUCT *params) { int varA, varB, varC; varA = params->A; varB = params->B; varC = params->C; } 

And I need to populate the structure elements from another routine, for example, "fileB.c", which contains the following:

 extern MY_STRUCT Data; int function(MY_STRUCT *params); /* Function */ void userMain(void) { Data.A = 1254; Data.B = 5426; Data.C = 1236; function(&Data); } 

But I get an error message:

"[Error] fileB.c E208: syntax error - token"; "inserted before" data

And if I get to the error, the compiler will take me to the declaration "extern MY_STRUCT Data;"

So my question is how to execute this function? I mean, how to populate the structure elements from another function in a different file than the file in which I declared the structure?

+4
source share
2 answers

We develop a bit in response @ pb2q:

Create filea.h file with (omitting definitions and stuff):

 struct MY_STRUCT { (blah blah blah ...) }; extern MY_STRUCT Data; 

This will declare the structure and let anyone who wants to know that the variable is declared in another file. Then insert file.c in the following lines

 #include "filea.h" // near the top (...) MY_STRUCT Data; // Somewhere meaningful 

This will actually declare the Data variable. Finally, in the fileb.c file, enter

 #include "filea.h" 

which allows you to use the Data variable.

0
source

When the compiler compiles the B.c file, it does not know about the typedef that you defined in the A.c file. Therefore, in the file B.c MY_STRUCT is an unknown type.

You must move the typedef to the general header and include it in the files fileA.c and fileB.c.

+5
source

All Articles