Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C project structure - header-per-module vs. one big header

I've worked with a number of C projects during my programming career and the header file structures usually fall into one of these two patterns:

  1. One header file containing all function prototypes
  2. One .h file for each .c file, containing prototypes for the functions defined in that module only.

The advantages of option 2 are obvious to me - it makes it cheaper to share the module between multiple projects and makes dependencies between modules easier to see.

But what are the advantages of option 1? It must have some advantages otherwise it would not be so popular.


This question would apply to C++ as well as C, but I have never seen #1 in a C++ project.

Placement of #defines, structs etc. also varies but for this question I would like to focus on function prototypes.

like image 562
finnw Avatar asked Jun 04 '09 12:06

finnw


People also ask

Are modules like header files?

Like header files, modules allow you to share declarations and definitions across source files. But unlike header files, modules don't leak macro definitions or private implementation details. Modules are easier to compose. They make it easier to control what is visible to consumers.

Why we use different header files in C?

C language has numerous libraries that include predefined functions to make programming easier. In C language, header files contain the set of predefined standard library functions. You request to use a header file in your program by including it with the C preprocessing directive “#include”.

Does order of header files matter in C?

Likewise, if your program needs to include multiple header files, the order in which they are included doesn't matter. Compatibility Note: Inclusion of standard header files in any order and any number of times works in any ISO C implementation.

How many headers does C have?

There are 19 header files in the Standard C Library.


2 Answers

I think the prime motivation for #1 is ... laziness. People think it's either too hard to manage the dependencies that splitting things into separate files can make more obvious, and/or think it's somehow "overkill" to have separate files for everything.

It can also, of course, often be a case of "historical reasons", where the program or project grew from something small, and no-one took the time to refactor the header files.

like image 77
unwind Avatar answered Sep 18 '22 23:09

unwind


Option 1 allows for having all the definitions in one place so that you have to include/search just one file instead of having to include/search many files. This advantage is more obvious if your system is shipped as a library to a third party - they don't care much about your library structure, they just want to be able to use it.

like image 27
sharptooth Avatar answered Sep 22 '22 23:09

sharptooth