Include headers in the header file?

I have several libraries made by me (geometry, linked list library, etc.). I want to make a header file to include them all in one lib.h. Can I do something like this:

#ifndef LIB_H_ #define LIB_H_ #include <stdio.h> #include <stdlib.h> #include <linkedlist.h> #include <geometry.h> .... #endif 

Then I could just reference this library and actually link to several libraries. Is it possible? If not, is there a way around it?

+7
c
source share
3 answers

Yes, that will work.

Note, however, that if you include many headers in this file and do not need each of them in each of the source files, this is likely to increase compilation time.

It also makes it difficult to determine which header files are specific to a particular source file, which can make code difficult to understand and debug.

+15
source share

Yes, it works and is actually used in most APIs. Remember what #include actually does (tell the preprocessor to immediately include the new file), and that should make sense. There is nothing to prevent several levels of inclusion, although implementations will have a (large) maximum depth.

As already noted, you must arrange the headers in logical groups.

+3
source share

The "correct path" to include (in A)

  • do nothing if: A does not reference B at all
  • do nothing if: The only link to B is in a friend's declaration
  • forward declare B if: A contains a pointer or reference B : B* myb ;
  • forward declare B , if: one or more functions have an object B / pointer / link as a parameter or as a return type: B MyFunction(B myb);
  • #include "bh" if: B is the parent class of A
  • #include "bh" if: A contains an object B: B myb;

From the cplusplus.com article you must finally read

+1
source share

All Articles