October 05, 2022

Creating header files in Ansi C

 



One of the serious problems within C programming is the art of creating a .h file. It is obvious that any programming projects needs to be split into multiple files and at the same time, most C newbies are not aware how to create these header files.
To make things more pleasant the first thing to know is, that a header file should contains only of the public visible functions. Let me give an example. The module contains three functions which are set(), get() and run(). The idea is that from the outside the set() function is executed first, then the run() function to activate the module and at the end the outside program is executing the get() function to retrieve the output of the program.
The include file consists only of these three prototypes but not all the additional functions and especially not of the variables from the module. All these things are declared private which means they are not mentioned in the header file but they are available in the .c file for the module.
The main advantage is, that things are easier to understand if they are reduced to its minimum. The outside program can include the .h file and it is only able to execute the mentioned functions but has no access to the modul's internal functions. Sure, the same functionality can be realized with the static statement which is often recommended in Online forum, but it is more easier to delete the function prototype from the header file at all. The cause is that by definition a header file has to obligation to communicate between a module and the outside program. And if no communication is needed about internal functions why should that are mentioned at all?
An interesting feature of the C language is, that the inner working of a module is very similar to a class known from object oriented languages. The idea is, that they are variables in this module which can be manipulated by the functions and that it not allowed to get access to these variables from the outside. A single module solves a clear defined problem and in the optimal case the code can be reused as a library.