Preprocessor directive #ifndef for C/C++ code

后端 未结 7 1691
傲寒
傲寒 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条回答
  •  时光说笑
    2021-02-12 23:04

    Consider this

    File foo.c:

    #include foo.h
    #include bar.h
    

    File bar.h

    #include 
    #include foo.h
    

    Now, when we compile foo.c, we have foo.h in there twice! We definitely don't want this, because all the functions will throw compile errors the second time around.

    To prevent this, we put the INCLUDE GUARD at the top. That way, if it's already been included, we define a preprocessor variable to tell us not to include it again.

    It's very common (often mandated), and very frustrating if someone doesn't put one in there. You should be able to simply expect that each .h file has a header guard when you included. Of course, you know what they say when you assume things ("makes an ass of u and me") but that should be something you're expecting to see.

提交回复
热议问题