3

Recently, I encountered such approach of managing headers. Could not find much info on its problems on internet, so decided to ask here.

Imagine you have a program where you have main.c, and also other sources and headers like: person.c, person.h, settings.c, settings.h, maindialog.c, maindialog.h, othersource.c, othersource.h

sometimes settings.c might need person.c and main maindialog.c.

Sometimes some other source might need to include other source files. Typically one would do inside settings.c:

//settings.c
#include "person.h"
#include "maindialog.h"

But, I encountered approach where one has global.h and inside it:

//global.h
//all headers we need
#include "person.h"
#include "maindialog.h"
#include "settings.h"
#include "otherdialog.h"

Now, from each other source file you only have to include "global.h" and you are done, you get functionality from respective source files. Does this approach with one global.h header has some real problems?

12
  • 1
    A common way of dealing with this is to wrap each header file in #ifndef xxxx / #define xxxx / #endif, so that even if it does get included twice the second time it will be ignored. Feb 26, 2014 at 21:26
  • 3
    The main problem is that it maximizes dependencies. You should be trying to minimize those. Feb 26, 2014 at 21:29
  • 2
    It would get thrown out of any code review I was in! Feb 26, 2014 at 21:32
  • 2
    Yes, include only the ones you need, and all the ones you need. Do not rely on some header including others. Feb 26, 2014 at 21:34
  • 2
    No, include guards for headers is a must. Otherwise you will run into multiple declaration errors and all kinds of troubles. A header needs to have include guards. Feb 26, 2014 at 21:36

2 Answers 2

3

This is to please both pedantic purists and lazy minimalists. If all sub-headers are done the correct way there is no functional harm including them via global.h, only possible compile time increase.

Subheader would be somewhat like

#ifndef unique_token
#define unique_token
#pragma once

// the useful payload

#endif
0
0

If there are common headers that all the source files need, (like config.h) you can do so. (but use it like precompiled headers...)

But by including unnecessary headers, you actually increasing the compilation time. so if you have a really big project and for every source file you including all the headers, compilation time can be very long...

I suggest not include headers unless you must. Even if you use type, but only for pointer or reference (especially in headers), prefer to use fwd declaration instead of include.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.