when creating header file sometimes I need to have access to other struct that I have declared in the other header files. Currently I organize it by having the #include Directive as a tree so that if I need to call the struct in b from a I place a header underneath b in main.
Probably a bad practice I am NEW to C.. don't be harsh :P where should I declared the struct for it to be accessible on the entire code?
should I create a header file with all my struct inside and then call it by doing an #include Directive
on all the header files? what is the best practice to declare a struct for a beginner.
I currently access to other struct declared in other header files as such
//main file
#include "b.h"
#include "a.h" <--- I had to put a.h underneath b.h to access to the struct in b.h named test
#include "c.h"
If the header file of
struct Aneeds to know aboutstruct B, then the header file which definesstruct Ashould itself contain an#includedirective that includes the header file ofstruct B, if it is defined in a different file.It should not be necessary to fiddle around with the order of the
#includedirectives in your main source file.As long as all header files have proper header guards that protect against the same header file being included twice, then this should not be a problem.
A header guard of the file
mystruct.hmay look like this:This will set a preprocessor macro when the header file is included for the first time, and when the file is included a second time, the preprocessor will see that this macro has already been set, and will ignore the rest of the file.
On many compilers, it is sufficient to simply write
into the header file as a header guard, instead of using the three lines mentioned further above. However, this may not work in all compilers. See the following C++ question (which should also apply to C) for further information:
#pragma once vs include guards?