#include in .h or .c / .cpp?

When coding in C or C ++, where should I have #include ?

callback.h:

 #ifndef _CALLBACK_H_ #define _CALLBACK_H_ #include <sndfile.h> #include "main.h" void on_button_apply_clicked(GtkButton* button, struct user_data_s* data); void on_button_cancel_clicked(GtkButton* button, struct user_data_s* data); #endif 

callback.c:

 #include <stdlib.h> #include <math.h> #include "config.h" #include "callback.h" #include "play.h" void on_button_apply_clicked(GtkButton* button, struct user_data_s* data) { gint page; page = gtk_notebook_get_current_page(GTK_NOTEBOOK(data->notebook)); ... 

Should everything be in .h or .c / .cpp or both, as I did here?

+70
c ++ c
Jun 08 '10 at 23:33
source share
4 answers

Put as much as possible in .c and as little as possible in .h . .C attachments are only included when this one file is compiled, but those included for .h must be included by every file that uses it.

+95
Jun 08 '10 at 23:36
source share

The only time you have to include a header in another .h file is if you need to access the type definition in that header; eg:

 #ifndef MY_HEADER_H #define MY_HEADER_H #include <stdio.h> void doStuffWith(FILE *f); // need the definition of FILE from stdio.h #endif 

If heading A depends on heading B, such as the example above, then heading A should include heading B directly. Do NOT try to order your included in .c file to satisfy the dependencies (that is, including the B header before the A header); itโ€™s a big antiquity of heartburn, awaiting its ministry. I'm serious. I have been to this film several times, and it always ends in Tokyo on fire.

Yes, this can lead to the fact that the files will be included several times, but if they have the proper guards enabled, configured to protect against several declaration / definition errors, then a few extra seconds of build time should not be worried. Trying to manage dependencies manually is a pain in the ass.

Of course, you should not include files that you do not need.

+27
Jun 09 2018-10-06T00:
source share

Put as much as possible into your cpp and only those needed by the hpp file in hpp. I believe that this will help speed up compilation, since hpp files will be cross-linked less.

Also consider using forward declarations in your hpp file to further reduce the include dependency chain.

+8
Jun 08 '10 at 23:37
source share

If I #include <callback.h> , I donโ€™t want to #include many other header files to get the code to compile. In callback.h you must include everything you need to compile. But nothing more.

Consider using forward declarations in your header file (for example, class GtkButton; ) is class GtkButton; , which will allow you to reduce the number of #include directives in the header (and, in turn, my compilation time and complexity).

+5
Jun 08 '10 at 23:36
source share



All Articles