Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include headers in header file?

Tags:

c

I have several libraries made by myself (a geometry library, a linked list library, etc). I want to make a header file to include them all in one lib.h. Could 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 one library and actually reference multiple libraries. Is this possible? If not, is there a way around it?

like image 810
Mohit Deshpande Avatar asked Apr 20 '10 23:04

Mohit Deshpande


3 Answers

Yes, this will work.

Note, however, that if you include a lot of headers in this file and don't need all of them in each of your source files, it will likely increase your compilation time.

It also makes it more difficult to figure out on which header files a particular source file actually depends, which may make code comprehension and debugging more difficult.

like image 80
James McNellis Avatar answered Nov 17 '22 00:11

James McNellis


The "right way" to include (in A)

  • do nothing if: A makes no references at all to B
  • do nothing if: The only reference to B is in a friend declaration
  • forward declare B if: A contains a B pointer or reference: B* myb;
  • forward declare B if: one or more functions has a B object/pointer/reference as a parameter, or as a return type: B MyFunction(B myb);
  • #include "b.h" if: B is a parent class of A
  • #include "b.h" if: A contains a B object: B myb;

From a cplusplus.com article you should definitively read

like image 34
ManuelSchneid3r Avatar answered Nov 16 '22 23:11

ManuelSchneid3r


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

As noted, you should organize your headers into logical groupings.

like image 41
Matthew Flaschen Avatar answered Nov 17 '22 00:11

Matthew Flaschen