Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I, or should I not include the same headers in different c files, which in turn are headers used in a main file?

I'm building a main.c file to make use of functions out of a few different .h files. A few of those .h files (or rather, their .c source files) use the same includes (the standard but also some others like )

My question is: Is it okay if I just include those once for all header files in my main.c, or should I let every .h file include them individually and not include them in my main.c (considering I only use functions from those header files)?

Or should I do both?

How I do it now is:

dist.c:

#include "dist.h"
#include  <stdio.h>
#include  <unistd.h>
#include  "rpiGpio.h"
#include <pthread.h>
#include  <wiringPi.h>
#include  <softPwm.h>

Then for another:

cmps.c:

#include "cmps.h"
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include "rpiGpio.h"

Then in my main.c:

#include    <stdio.h>
#include    <stdlib.h>
#include    "dist.h"
#include    "cmps.h"

Thanks in advance!

like image 963
Guinn Avatar asked Jan 04 '15 18:01

Guinn


1 Answers

You should include standard headers above your own headers, and you should include all the dependencies for a file in that file. If you change the includes in one of your file, it shouldn't affect any other files. Each file should maintain its own list of header dependencies.

If, in your example, dist.h includes <stdio.h>, you should not rely on this outside dist.h. If you change dist.h so that it no longer depends on <stdio.h> and remove that #include, then your program breaks.

like image 121
meagar Avatar answered Sep 27 '22 22:09

meagar