Tuesday, June 3, 2008

header guard

When working on large software development projects, you often include header files from various parts of the source repository and a cool trick to avoid redefinitions is by use of "header guard".

The concept is fairly simple. Consider the following header files:
foo.h
-----
typedef struct {
int x;
} foo;


bar.h
-----
#include "foo.h"
typedef struct {
foo f;
} bar;


Now when you include these files as follows:
mainfile.c
----------
#include "foo.h"
#include "bar.h"
.....
.....


Obviously you will run into a "redefinition" error when compiled.

The solution:
Place
#ifndef /* unique symbol is generally some form of the file name */
#define
at the beginning of the header file, and
#endif
at the end of the header file.

What this does is that the first time the unique symbol is encountered, the symbol gets defined and none of the definitions in the header file are then redefined.

So foo.h would look like:
#ifndef _FOO_H_
#define _FOO_H_
typedef struct {
int x;
} foo;
#endif /* _FOO_H_ */


and bar.h is like:
#ifndef _BAR_H_
#define _BAR_H_
#include "foo.h"
typedef struct {
foo f;
} bar;
#endif /* _BAR_H_ */

No comments: