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:
.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 #define
s, struct
s etc. also varies but for this question I would like to focus on function prototypes.
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.
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”.
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.
There are 19 header files in the Standard C Library.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With