Saturday, August 29, 2009

Header Files in C

This post might be helpful if you are reading a C header file or wish to write one and baffeled to see unknown keywords and begin to think of header files as alien objects in C.

Header files are just another C files which commonly contain function declarations, identifiers and variables.

A Programmer will prefer to write a header file than having these declarations in main stram code either to give the program more structured appearance by using standardized identifiers or there are more than one source files which aims to use these identifiers or functions, these files can rather include a single header file whenever the identifiers are required.

At the time of compilation, the task of including header files is taken care of by pre-processor. A pre-processor is a separate program which is invoked by the compiler prior to the compilation process. A C pre-processor will modify the source code before handling it to the compiler.

Pre-processsor deals with three things,
Directives: which instructs the pre-processor to do the needful; they always begin with ‘#’ (Read: Sharp). Examples of directives are #include, #define, #if etc.
Constants and Macros : they are defined using #define. A task of pre-processor is to take care of these  #defined macros and constants.

Moving back to header files... Whenever a  ‘#include’ statement is seen by the pre-processor, the content of the header file is directly placed into the current file. There are a few directives which shall catch your attention whenever you read a standard (well-written) header files, they are related to conditional compiling of the codes.
-#if -
#if
....
#else
....
#endif

They have the same meaning as normal if  else statement with the only BIG difference being that they are not conditionals for execution but conditionals for compilation. If the after #if has a zero value, compiler will skip compiling the code till #else, and if #else is not present then till #endif

Another Similar directive is -#ifndef-
When a header file is #include'd in multiple source files, the result is that, all the variables, identifiers and functions are defined multiple times. The pre-processor , with the help of #ifndef directive can ensure that each header file is included once and only once. Here's an example showing use of #ifndef [ Read:  if NOT defined ]


#ifndef _FILENAME_H
#define _FILENAME_H
....
#endif

This simply means : include the following content only if a particular expression is undefined; then, if it is undefined you can define the expression. This ensures that the code in the #ifndef is included only the first time the file is loaded and not as many times as the #include statement is compiled.. [Rather pre-processed ]

[ Readers: This is out of my understanding. Corrections are welcome, I might be wrong at a place or two… or even entirely :) :)  ]

- Happy Programming -

0 comments: