Why the C structure definition in the implementation file is unavailable? -
i give following example illustrate question:
1) a.h structure declared
a.h struct a_structure; typedef struct a_structure *a_structure_ptr; 2) b.c structure definition implemented
#include "a.h" struct a_structure { int a; int b; int c; }; 2) main.c structure invoked
#include <stdlib.h> #include "a.h" int main () { struct a_structure b; return 0; } however, cannot compile these c codes receive following error message:
>main.c(6): error c2079: 'b' uses undefined struct 'a_structure' any ideas? thank in advance.
edit:
#include <stdlib.h> #include "a.h" int main () { struct a_structure *b=0; b=(struct a_structure*)malloc(12); b->a=3; free(b); return 0; } i tried create structure in way still failed.
you need this:
struct a_structure { int a; int b; int c; }; in a.h
this typical approach when defining structs
if you're trying implement opaque pointer, need function instantiates a_structure , returns pointer, functions manipulate a_structure pointers:
in a.h
a_structure_ptr createa(int a, int b, int c); void freea(a_structure_ptr obj); void seta_a( a_structure_ptr obj, int ); int geta_a( a_structure_ptr obj ); // etc. in b.c
a_structure_ptr createa(int a, int b, int c) { a_structure_ptr s = malloc( sizeof(a_structure) ); s->a = a; s->b = b; s->c = c; } void freea(a_structure_ptr obj) { free( obj ); } void seta_a( a_structure_ptr obj, int ) { obj->a = a; } in main.c
int main () { struct a_structure *b = createa( 1, 2, 3); seta_a( b, 3 ); freea(b); return 0; }
Comments
Post a Comment