Can you explain why the struct Test is incomplete and how to remove the error? Is the error related to declaration in test.h or to definition in test.c? I tried to move the definition code to header file but then createTest does not know type Test or if I move the function to header there is the error multiple definition of createTest
test.h
typedef struct STest Test;
test.c
typedef struct STest {
int v;
char *str;
}Test;
Test *createTest(int v,char *str) {
Test *t=(Test*)malloc(sizeof(Test));
t->v=v; // error
t->str=str; // error
return t;
}
main function (main.c)
error: main.c|44|error: dereferencing pointer to incomplete type
If you don't define the structure in the header file it will not be visible from your main.c
.
You need to do the following
Point 1. Put the structure definition in the test.h
header file. use include guard also.
#ifndef __MY_HDR_H_
#define __MY_HDR_H_
typedef struct STest {
int v;
char *str;
}Test;
#endif //__MY_HDR_H_
[EDIT: Also, you need to add the function prototype for createTest()
in the .h
file]
Point 2. include test.h
in test.c
and main.c
.
Point 3. Compile using
gcc main.c test.c -o output
Standard Warning : Please do not cast the return value of malloc()
and family.