Header Guard 是為了避免重複include 同一個head file ,

以一個例子來說 , 

                           #include "A.h"          #include "A.h"
class A                    class B                 #include "B.h"
{                          {
    int x;                      A a;
    public:                    int y;                   A a;
};                              public:                 B b;
                            };


     A.h                       B.h                      htest.cc
當我們對htest.cc進行compile時 , 我們可能會得到以下的錯誤 :
In file included from B.h:1,
                       from htest.cc:2:
A.h:2: error: redefinition of `class A'
A.h:2: error: previous definition of `class A'
The class A is being defined twice, once when it is included in htest.cc and once when it is included into B.h which is included in htest.cc.

A better way to solve this problem is through the use of header guards. Header guards are little pieces of code that protect the contents of a header file from bein
g included more than once.
use the example above , the file become :
#ifndef A_H                #ifndef B_H
#define A_H               #define B_H 

                                   #include "A.h"           #include "A.h"
class A                         class B                      #include "B.h"
{                                 {
    int x;                            A a;
    public:                          int y;                     A a;
};                                     public:                   B b;
                                    };

#endif /* A_H */           #endif /* B_H */

     A.h                           B.h                            htest.cc

Some analysis is in order. The first time one of the unique symbols in a header guard is encountered, the #ifndef statement is true. The symbol is not defined. 
Because of that, all of the code between the #ifndef and#endif is included and sent to the compiler. 
If the symbol were defined, the code between the directives would be ignored.

ref : http://faculty.cs.niu.edu/~mcmahon/CS241/c241man/node90.html

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 JerryCheng 的頭像
    JerryCheng

    KwCheng's blog

    JerryCheng 發表在 痞客邦 留言(0) 人氣()