Jim said:
Hi:
Do we have some common style for includes when working on a project
with lots of c and h files. Wat I mean is do we have a rule in C when
a file includes several files and those file in turn can call back it.
So do we keep the includes in the source file or in its header file
and just call the header from the c file. Are there any more rules
when we go for includes. Thanx to yu all who bother to share....
Having a lot of includes can increase compile time. It's a good idea
to minimize the number of header files that are included in other
header files, or not have any at all. Let's say you have a.h, b.h,
and b.c, and both b.h and b.c are dependent on a.h so both files
include a.h. Everytime you compile b.c, a.h is going to be opened
and parsed twice. If you add another header to b.c that includes a.h,
it's going to be parsed three times. If that header is also dependent
on b.h, then a.h is going to be parsed four times. It only needs to be
read once, so it's a just waste of time to include it all those times.
You can decide not include any headers in other headers. This means
you have to include the headers in the right order in your source files.
a.h would have to be included before b.h in every source file that
needs b.h. So that can be a real pain. You can get around that by
just making one header file with all the headers for the entire project
included in it and just include that in every source file. But then
every file you compile has to read every single header file every
time. If your compiler supports precompiled headers then it will
take of all that in one shot and you don't have to worry about it.
If you don't have precompiled headers and you don't want to include
every file every single time and you don't want to manually arrange
all of the headers for every file you can use external include
guards instead of the usual internal ones. This way, if the file
has already been included, it won't have to be opened at all. The
problem with this is that every time you include a file in a header
you have to wrap it in external guards:
#ifndef A_H
#include "a.h"
#endif
#ifndef B_H
#include "b.h"
#endif
If the code is well organized and modular then you won't really
have to worry about any of this. You just want to avoid including
files dozens or hundreds of times, which can happen if you have a
lot of includes in headers.
In short, the only rule with header files is that you don't want
them to increase compile time unnecessarily.
Matt Gregory