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 A
needs to know about struct B
, then the header file which defines struct A
should itself contain an #include
directive that includes the header file of struct B
, if it is defined in a different file.
It should not be necessary to fiddle around with the order of the #include
directives 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.h
may look like this:
#ifndef MYSTRUCT_H_INCLUDED
#define MYSTRUCT_H_INCLUDED
//the main content of the header file goes here
#endif
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
#pragma once
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: