/

Using C Header Files to Organize Your Program

Using C Header Files to Organize Your Program

As your C program grows larger, it becomes essential to organize it into multiple files. This is where C header files come into the picture.

A header file in C is a separate file that contains declarations instead of function implementations. It looks like a regular C file but has a .h extension instead of .c.

When you include a header file, you can access the declarations written in that file. For example, when you used the printf() function, you included the stdio.h header file using the following preprocessor directive:

1
#include <stdio.h>

To include your own header files, you use quotes instead of angle brackets. For instance:

1
#include "myfile.h"

This will look up the myfile.h file in the current folder. You can also use a folder structure for libraries, like this:

1
#include "myfolder/myfile.h"

Let’s go through an example to illustrate how header files work. Consider the following program that calculates the number of years since a given year:

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>

int calculateAge(int year) {
const int CURRENT_YEAR = 2020;
return CURRENT_YEAR - year;
}

int main(void) {
printf("%u", calculateAge(1983));
}

Suppose you want to move the calculateAge function to a separate file. You would create a calculate_age.c file with the function implementation:

1
2
3
4
int calculateAge(int year) {
const int CURRENT_YEAR = 2020;
return CURRENT_YEAR - year;
}

Additionally, create a calculate_age.h file and include the function prototype, which is the same as the function declaration in the .c file but without the body:

1
int calculateAge(int year);

Now, in the main .c file, you can remove the calculateAge() function definition and import the calculate_age.h header file, which will make the calculateAge() function available:

1
2
3
4
5
6
#include <stdio.h>
#include "calculate_age.h"

int main(void) {
printf("%u", calculateAge(1983));
}

When you compile a program composed of multiple files, remember to list all the files in the command line, like this:

1
gcc -o main main.c calculate_age.c

For more complex setups, you may need a Makefile to instruct the compiler on how to compile the program.

tags: [“C programming”, “C header files”, “organizing code”, “function declaration”, “function implementation”]