file - Proper way to declare and use structures in C project? -
i building project trying organize follows:
main.c globals.h structures.h functionset1.c, functionset1.h functionset2.c, functionset2.h etc.
i thought define structure type in structures.h:
struct type_struct1 {int a,b;}; // define type 'struct type_struct1'
then declare function1()
returning structure of type type_struct1
in functionset1.h:
#include "structures.h" struct type_struct1 function1(); // declare function1() returns type 'struct type_struct1'
then write function1()
in functionset1.c:
#include "functionset1.h" struct type_struct1 function1() { struct type_struct1 struct1; // declare struct1 type 'struct type_struct1' struct1.a=1; struct1.b=2; return struct1; }
edit: corrected code above, compiler returns
306 'struct' tag redefined 'type_struct1' structures.h
is file set practice ? practice manage structures ?
your general structure looks good. 1 thing need do, zenith mentioned, put include guards header files. is set of #define's make sure contents of header not included more once in given file. example:
structures.h:
#ifndef structures_h #define structures_h struct type_struct1{ int a,b; }; ... // more structs ... #endif
functionset1.h:
#ifndef function_set_1_h #define function_set_1_h #include "structures.h" struct type_struct1 function1(); ... // more functions in fucntionset1.c ... #endif
main.c:
#inlcude <stdio.h> #include "structures.h" #include "functionset1.h" int main(void) { struct type_struct1 struct1; struct1 = function1(); return 0; }
here, main.c includes structures.h , functionset1.h, functionset1.h includes structures.h. without include guards, contents of structures.h appear twice in resulting file after preprocesser done. why you're getting "tag redefined" error.
the include guards prevent these type of errors happening. don't have worry whether or not particular header file included or not. particularly important if you're writing library, other users may not know relationship between header files.
Comments
Post a Comment