0

I've been building many C++ projects for my university recently. They were consisted of multiple files with one Makefile. All in a prj folder with Makefile within, the source files in src folder and headers in inc folder. Makefile compiled it to object files in obj folder and than linked it to the final program.

I do got many strange errors which I broke down into that, e.g. I've included Matrices.h in Vector.h file and Vector.h in a Matrix.h. The compiler than said that some methods do not exist in a Matrix class.

I have to include Vector.h in Matrix.h. Then, include Matrix in main.cpp. I use sqrt() and pow() functions in all files.

Now I wonder is it proper to avoid declaring continously <cmath> library in Vector.h, then Matrix.h and finally in main.cpp? I'd rather just declare it in Vector.h and leave it. The complier is g++ and its Linux Debian.

I use preprocessor directives:

#ifndef VECTOR_HH //or MATRIX_HH etc.
#define VECTOR_HH

#include <cmath>

//class body


#endif`
Kamil Kuczaj
  • 193
  • 1
  • 8
  • [This](http://stackoverflow.com/questions/625799/resolve-circular-dependencies-in-c) might help you resolve situations like this. – Beta Carotin Apr 26 '15 at 09:44
  • That definitely helped a bit. However, what I particularly meant, was if I include library in a file that is included in another file, do I need to include that library again if the latter file uses functions from that library. Is it correct, if I omit it, since it is included in the include file? – Kamil Kuczaj Apr 26 '15 at 10:56
  • Yes, you can safely omit any files that are already included. – Beta Carotin Apr 26 '15 at 11:04
  • Is it a good practice? – Kamil Kuczaj Apr 26 '15 at 12:18
  • I would say it is common practice, but I can't give you a well-founded answer to that. – Beta Carotin Apr 26 '15 at 12:50

2 Answers2

0

To be independent of #include changes in included files, you should include-what-you-use.

  • So I should include, e.g. library wherever I use one of its functions, regardless of included custom headers, should I? – Kamil Kuczaj Apr 26 '15 at 15:52
0

Good practice is to define a generic header file, where you can include all the necessary header files at one, along with header guards.

Consider for example common-hdr.h wherein you declare

#ifndef COMMON-HDR_HH
#include <cmath>
#include "Vector.h"
#include "Matrix.h"

// other common files

#endif

Now you free to include just common-hdr.h to all files.

kspviswa
  • 637
  • 3
  • 13