Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming with just header files?

Tags:

c

If a header file is just a piece of code that gets pasted onto another when I use #include then what is stopping me from programming in C using only .h files? You can even #include into other header files!

I assume there must be some performance or workflow reason why this isn't more common, but if it exists I do not know what it is.

Therefore my question is: What is the reason people don't program entire applications with just header files?

like image 682
Althis Avatar asked Apr 24 '26 04:04

Althis


1 Answers

Header files come with the concept of modularisation, i.e. of separating the source code of a large program into several independent parts, i.e. translation units. Thereby, implementation details are hidden to other translation units, and dependencies are dramatically reduced. But: if a translation unit A needs to call a function from another translation B, it needs to have the function prototype of the respective function, i.e. the function without the body - something like int functionFromB(int x); in order to tell the compiler how to call it. So translation unit A could simple write this prototype at the beginning; but usually functions from translation unit B (e.g. B.cpp) are exposed in a header file B.h, which comprises all the "public" functions of B in form of function prototypes. Same applies to type definitions and (global) variables. Then A simply can include B.h in order to have all the function prototypes et al. available without the necessity of knowing all the implementation details (like the function bodies).

So you can write a large program completely in .h-files; yet you have to tell the compiler to treat them as translation units (usually only .cpp-files are treated as such), and you still have to provide function prototypes et al...

With translation units, you have separate / independent modules. This is in contrast to a large monolithic block, which you get when you "paste" all the chunks of your program spread over different .h-files by #include-ing them "together". You can compile / test / distribute translation units separately, whereas a monolithic block cannot be compiled / tested / distributed partly.

like image 158
Stephan Lechner Avatar answered Apr 26 '26 20:04

Stephan Lechner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!