Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should a .c file not have an associated .h file?

Tags:

c

header-files

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?

like image 652
C. Ross Avatar asked Oct 28 '10 14:10

C. Ross


People also ask

Should every C file have a header 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.

Why shouldn't you #include a .C source file?

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.

Which of the following should not be in a header .h file?

Header files should never contain object definitions, only type definitions and object declarations.

Why do we need .h file in C?

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.


2 Answers

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.

like image 159
paxdiablo Avatar answered Oct 10 '22 18:10

paxdiablo


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.

like image 22
Necrolis Avatar answered Oct 10 '22 19:10

Necrolis