Redefinitions, Redclarations , Conflicting types


Consider what happens if a C source file includes both a.h and b.h, and also a.h includes b.h (which is perfectly sensible; b.h might define some types that a.h needs). Now, the C source file includes b.h twice. So every #define in b.h occurs twice, every declaration occurs twice (not actually a problem), every typedef occurs twice, etc. In theory, since they are exact duplicates it
shouldn’t matter, but in practice it is not valid C and you will probably get compiler errors or at least warnings.

The solution to this problem is to ensure that the body of each header file is included only once per source file. This is generally achieved using preprocessor directives. We will define a macro for each header file, as we enter the header file, and only use the body of the file if the macro is not already defined. In practice it is as simple as putting this at the start of each header file:



#ifndef FILENAME_H
#define FILENAME_H

and then putting this at the end of it:

#endif

replacing FILENAME H with the (capitalised) filename of the header file, using an underline instead of a dot. Some people like to put a comment after the #endif to remind them what it is referring to, e.g.

#endif /* #ifndef FILENAME_H */

Personally I don’t do that since it’s usually pretty obvious, but it is a matter of style.

You only need to do this trick to header files that generate the compiler errors, but it doesn’t hurt to do it to all header files.

No comments:

Post a Comment