Header Files

Header files allow you to define things like functions, constants and data types that you wish to make use of at several points in your program. Header files end with the .h extension. It is normal to provide the prototype of a function in a header file and then provide the implementation in a .c file. For example:

file foo.h:

/*This header file defines the function foo*/

/*foo is a universally useless function*/
int foo(float f);


file foo.c:
/*This file implements the function foo*/

#include "foo.h"
#include 

int foo(float f)
{
    printf("foo!\n");
    return 3;
}

Notice that the header file is included in the implementation file. Also notice that the protoype must be terminated with a semi-colon. The implementation uses opening and closing braces.

Often, several related functions will be defined in one header file and them implemented in the associated c file. When a programmer wants to use the functions elsewhere in the program, he/she merely includes (#include) the header file at the start of the .c file. The functions can then be used with the code in this file. For example:

file sample.c:

/*Here we implement the function sample*/
#include "sample.h"
#include "foo.h"

void sample()
{

   foo(4.3); //this function can be used here because its header
             //file has been included above
}

Header files are also used for declaring constants, data types and any other data that will be shared amongst multiple implementation files.

next


 home                      table of contents                      about