Most of the time in C programming it seems that there will be one header file (.h
) per code file (.c
), for the function prototypes at least.
When would it be appropriate to not have a header file for a code file?
If your file exposes an interface - that is, if it has functions which will be called from other files - then it should have a header file. Otherwise, it shouldn't.
It's much easier to navigate a central list of source files in one place, than in the include directives from a series of files. All this is to say that to include . h files, rather than . c files, decreases the likelihood of errors, and makes debugging easier.
Header files should never contain object definitions, only type definitions and object declarations.
Header files serve two purposes. System header files declare the interfaces to parts of the operating system. You include them in your program to supply the definitions and declarations you need to invoke system calls and libraries.
There's a few use cases for this. The most obvious is that your main program rarely needs a header file.
The second is where you don't have one header for each C file. I've put together libraries before (let's say a BTree library for the purposes of this answer) where each individual function is in its own source file but there's a library-wide header file, something like:
btree.h
btree_priv.h
btreeInit.c
btreeDestroy.c
btreeConfig.c
and so on. The private header file is for stuff that need to be shared between the code but is not to be published in the API.
most obviously when the .c
is fully self contained and does not need to have prototypes or extern's for other .c
files. this basically is only for very small programs, or those that export via a def file to plugin in to a predefined interface.
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