Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to not create a separate interface (.h) and implementation (.c) in C? [closed]

I'm currently transitioning to working in C, primarily focused on developing large libraries. I'm coming from a decent amount of application based programming in C++, although I can't claim expertise in either language.

What I'm curious about is when and why many popular open source libraries choose to not separate their code in a 1-1 relationship with a .h file and corresponding .c files -- even in instances where the .c isn't generating an executable.

In the past I'd been lead to believe that structuring code in this manner is optimal not only in organization, but also for linking purposes -- and I don't see how the lack of OOD features of C would effect this (not to mention not separating the implementation and interface also occurs in C++ libraries).

like image 760
TolkienWASP Avatar asked Jan 08 '23 15:01

TolkienWASP


1 Answers

There is no inherent technical reason in C to provide .c and .h files in matched pairs. There is certainly no reason related to linking, as in conventional C usage, neither .c nor .h files has anything directly to do with that.

It is entirely possible and potentially advantageous to collect declarations related to multiple .c files in a smaller number of .h files. Providing only one or a small number of header files makes it easier to use the associated library: you don't need to remember or look up which header you need for the declaration of each function, type, or variable.

There are at least three consequence that arise from doing that, however:

  • you make it harder to determine where to find the implementations of functions declared in collective headers.
  • you make your project more susceptible to mass rebuilding cascades, as most object files depend on one or more of a small number of headers, and changes or additions to your function signatures all affect one of that small number of headers.
  • the compiler has to spend more effort digesting one large header with all the library's declarations than to digest one or a small number of headers focused narrowly on the specific declarations used in a given .c file, as @ChrisBeck observed. This tends to be much less of a problem for C code than it does for C++ code, however.
like image 157
John Bollinger Avatar answered Jan 17 '23 14:01

John Bollinger