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?
>Solution :
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.