I just started learning C and have trouble understanding the concept of header and source files, specifically which ones I'm supposed to include where.
Suppose I have the classes A and B, each of whose contents are seperated into a header file and a source file, and I have a file in which I want to use those classes.
├ A.h
├ A.cpp
├ B.h
├ B.cpp
└ Main.cpp
Which file do I need to include where, and is it possible to compile/link all files with a single command?
CodePudding user response:
Which file do I need to include where
#include
directive in fact is very simple preprocessor directive, which just adds content if the specified file into the target file. Conventionally you keep declaration of functions in a header file and definition of the said functions in the corresponding cpp
file, and thus you at least want to have the header included there (in your case A.cpp
includes A.h
and B.cpp
includes B.h
). Additionally you include these headers in any file where you use the functions declared there (e.g. if you use declaration of A.h
and B.h
in Main.cpp
you include those files as well).
P.S. You, however, can define everything right in the header file, next to declarations, but as I said earlier preprocessor doesn't do anything fancy - it just adds the content of the include in the target file, and you usually don't want to have all definitions in place, because each translation unit which has it included will have the same definitions repeated over and over again.
CodePudding user response:
You include what you need.
If A.cpp
needs A.h
then it should include it. Same for B.cpp
probably needing to include B.h
.
If Main.cpp
uses A
and B
then it should include A.h
and B.h
.
Main.cpp
should not rely on indirect includes. For example of A.h
does include B.h
then Main.cpp
using both A
and B
should still include A.h
and B.h
even if the code would compile if Main.cpp
would only directly include A.h
(and by that also indirectly including B.h
.)
In Which order?
If you follow the rule of always including what you use (rather than relying on indirectly including a header or rely on some other header being included before) then the order of #include
directives should not matter. Changing order of includes breaking a build hints on a problem with includes in one of the headers that should be fixed. If you do things right then order of includes is just a matter of style.