Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Header & Source Files – What To Include And In Which Order

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading