Categories
c programming tips and tricks

Testing for header inclusion

C uses “header” (“.h”) files that may contain declarations of functions and constants. A header file may be included in a C code file by importing it using its name between angle brackets when it is one of the headers supplied with your compiler (#include < string.h >) or between double-quotes when it is a header that you have written: (#include “mystring.h”). But in a complex program containing many source code files, there is the danger that you may include the same header file more than once.

3-3

Suppose we have a simple header file, header1.h, that contains the following definitions:

typedef int T;
typedef float F;
const int T_SIZE = sizeof(T);

Then we make another header (header2.h) that contains this:

#include "header1.h"
typedef struct {
	T t;
	F f;
} U;
const int U_SIZE = sizeof(U);

Now, if in our main program, main.c, we have this:

#include "header1.h"
#include "header2.h"

When we compile the program, we will get a compilation error, because T_SIZE will be declared twice (because its definition in header1 is included in two different files). We have to include header1 in header2 in order to get header2 to compile in circumstances where we don’t use header1. So, how can we fix this problem? The way around this is to define a “guard” macro that encloses all of the definitions in a header file, so that header1 becomes:

#ifndef HEADER1_H
#define HEADER1_H
typedef int T;
typedef float F;
const int T_SIZE = sizeof(T);
#endif

This sort of problem is so common that many IDEs such as NetBeans will do this for you when you create a new header. If you create the header file yourself, however, you need to do this explicitly. To avoid this sort of error, you must make sure that all your header definitions are within the “guard” #ifdef.

Leave a Reply

Your email address will not be published. Required fields are marked *