Discussion
Team LiB
Previous Section Next Section

Discussion

Each header file should be guarded by an internal #include guard to avoid redefinitions in case it is included multiple times. For example, a header file foo.h should follow the general form:



#ifndef FOO_H_INCLUDED_


#define FOO_H_INCLUDED_


// … contents of the file …


#endif



Observe the following rules when defining include guards:

  • Use a unique guard name: Make sure it is unique at least within your application. We used a popular convention above; the guard name can include the application name, and some tools generate guard names containing random numbers.

  • Don't try to be clever: Don't put any code or comments before and after the guarded portion, and stick to the standard form as shown. Today's preprocessors can detect include guards, but they might have limited intelligence and expect the guard code to appear exactly at the beginning and end of the header.

Avoid using the obsolete external include guards advocated in older books:



#ifndef FOO_H_INCLUDED_         // NOT recommended


#include "foo.h"


#define FOO_H_INCLUDED_


#endif



External include guards are tedious, are obsolete on today's compilers, and are fragile with tight coupling because the callers and header must agree on the guard name.

    Team LiB
    Previous Section Next Section