Naming Include Guards

前端 未结 9 1141
忘了有多久
忘了有多久 2020-11-29 08:37

How are C++ include guards typically named? I tend to see this a lot:

#ifndef FOO_H
#define FOO_H

// ...

#endif

However, I don\'t think

相关标签:
9条回答
  • 2020-11-29 08:39

    From my own experience, the convention is to name the inclusion guards after the header file containing them with the exception that the name is all in caps and the period is replaced with an underscore.

    So test.h becomes TEST_H.

    Real life examples of this include Qt Creator, which follows this convention when auto-generating class header files.

    0 讨论(0)
  • 2020-11-29 08:40

    Usually people do that by file name so that each file's code only gets compiled and added once. You could make FOO_H whatever you want, but almost everything I've ever coded or seen has used the file name. Just make sure it's unique because you don't want your FOO_H conflicting with someone else's FOO_H.

    0 讨论(0)
  • 2020-11-29 08:44

    Replace FOO_H with FOO_H_INCLUDED and it's clearer.

    0 讨论(0)
  • 2020-11-29 08:52

    Look at the code that #include's your header.

    If it is something like:

    #include "mylib/myheader.h"
    

    mylib/myheader.h is already a unique name. Just capitalize and replace / and . with _

    #define MYLIB_MYHEADER_H
    

    If you have two headers on your include path with the same name relative to the include path, you already have a collision at that level.

    0 讨论(0)
  • 2020-11-29 08:52

    I usually look what time it is and just append that to the end of it, i.e. FOO_H_248, it's an extra precaution, and you'll never have to remember it anyway, so you don't need to worry about the fact that it's cryptic.

    0 讨论(0)
  • 2020-11-29 08:58

    Taken directly from google's style guide:

    All header files should have #define guards to prevent multiple inclusion. The format of the symbol name should be <PROJECT>_<PATH>_<FILE>_H_. To guarantee uniqueness, they should be based on the full path in a project's source tree. For example, the file foo/src/bar/baz.h in project foo should have the following guard:

     #ifndef FOO_BAR_BAZ_H_
     #define FOO_BAR_BAZ_H_
     ...
     #endif  // FOO_BAR_BAZ_H_
    

    I use this style in my own projects.

    0 讨论(0)
提交回复
热议问题