Preprocessor directive #ifndef for C/C++ code

后端 未结 7 1719
傲寒
傲寒 2021-02-12 22:25

In eclipse, whenever I create a new C++ class, or C header file, I get the following type of structure. Say I create header file example.h, I get this:

7条回答
  •  旧时难觅i
    2021-02-12 23:01

    This is an include guard. It guarantees that a header is included no more than once.

    For example, if you were to:

    #include "example.h"
    #include "example.h"
    

    The first time the header is included, EXAMPLE_H_ would not be defined and the if-block would be entered. EXAMPLE_H_ is then defined by the #define directive, and the contents of the header are evaluated.

    The second time the header is included, EXAMPLE_H_ is already defined, so the if-block is not re-entered.

    This is essential to help ensure that you do not violate the one definition rule. If you define a class in a header that didn't have include guards and included that header twice, you would get compilation errors due to violating the one definition rule (the class would be defined twice).

    While the example above is trivial and you can easily see that you include example.h twice, frequently headers include other headers and it's not so obvious.

提交回复
热议问题