Struct in header file | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 8

Struct in header file

Can i declare a struct in a header file test.h, define it in test.c file and after that use the struct in otherFile.c where i included the header file test.h. Or do i have to define the struct in the header file completly to use it in .c files where i included the header?

12th Nov 2019, 9:32 PM
Jnn
Jnn - avatar
6 Answers
+ 2
I have done that: In header file test.h( surrounded by #ifndef #define .... #endif): typedef struct mystruct mystruct; void mystruct func(); And in test.c file: struct { int x; int y}; void mystruct func(){ ..... definition } How would i use this function and struct in otherFile.c? (And btw thank you very much for your help :D)
12th Nov 2019, 10:07 PM
Jnn
Jnn - avatar
+ 1
I also have funktion declarations in the header file which i define in test.c. When i also include test.c the Compiler tells me that i have multiple definitons of the functions Is it even possible to declare the functions and the struct in the same test.c file and use the functions and the struct in otherFile.c ?
12th Nov 2019, 9:52 PM
Jnn
Jnn - avatar
+ 1
And of course i included test.h in test.c
12th Nov 2019, 10:12 PM
Jnn
Jnn - avatar
+ 1
Thank you thats actually my problem.. The complier tells me "error: dereferencing pointer to incomplete type 'mystruct'" (I thought thats not the problem so i used easier examples) My files actually look like this: test.h : typedef struct struct1 struct1; typedef struct struct2 struct2; struct2* func(struct1* s); test.c: struct struct1 { struct2* x; }; struct struct2 { struct2* y; }; struct2* func(struct1* s){ return s->x; } Otherfile.c #include "test.h" int main(){ ... struct1* 'm' points to allocated memory..... m->x } This only works when i define the struct already in the header file. When i do it like this the compiler tells me that im dereferencing pointer to incomplete type struct1 with "m->x"
13th Nov 2019, 11:05 AM
Jnn
Jnn - avatar
+ 1
Thank you that was really helpful 😊
13th Nov 2019, 12:10 PM
Jnn
Jnn - avatar
0
It always works when i define the struct in the header and only the function in test.c But when i define everything in c the otherFile.c it does not So i thought its maybe not possible that way (But could also be another problem then)
12th Nov 2019, 10:26 PM
Jnn
Jnn - avatar