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
#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:
Post a Comment