Names used for include guards?

前端 未结 3 1286
陌清茗
陌清茗 2021-01-22 15:25

Are there any guidelines people tend to follow when selecting a name for their include guard? I don\'t understand why the name for the .h file will slightly dif

相关标签:
3条回答
  • 2021-01-22 15:59

    The important thing about the symbols used for include guards is that they are unique. That means that not only do the include guards for every header file (including any library headers your project may be using) need to be unique, they must also not clash with any other symbols used anywhere in your project.

    There are a couple common ways people go about ensuring uniqueness:

    1) Use something like <PROJECT_NAME>_<FILE_NAME> (i.e. MYPROJECT_SPHERE_H)

    Including your project name will help ensure your include guard doesn't clash with that of another "sphere.h" you include from some library. Using the file name and extension makes it easy to create include guards when adding a new header to your project and makes it very unlikely that name will be used anywhere else in the project (for a variable, function, etc.).

    2) Use a UUID (i.e. GUARD_0be96322_7238_49d2_a967_e8fd9907cca1)

    This is a very safe approach, since UUIDs are extremely unlikely to ever collide. It is harder to read though, and means you have to dig out your UUID generator whenever you create a new file.

    0 讨论(0)
  • 2021-01-22 16:01

    Most modern compiler support the #pragma once directive that could be used instead. See: https://en.wikipedia.org/wiki/Pragma_once

    0 讨论(0)
  • 2021-01-22 16:13

    To pick a good name for a header guard, consider these points:

    1) the name has to be unique, so make it long and specific. That can usually be accomplished by including things like project name, module name, file name and file extension.

    2) make sure you don't use names reserved for the implementation. So, names starting with underscore followed by a capital letter are out, as are names containing double underscore, names ending in _t and a few more.

    3) make the name make sense to human readers. So don't just generate a UUID and use that.

    4) convention dictates that you use all uppercase for macros to distinguish them from ordinary variables.

    Underscores are not needed, as such, but since you cannot use spaces in macro names, underscores serve as a good alternative to keep things readable.

    So, IMHO, a good guard name for a file foo.h in a submodule bar inside project baz is: BAZ_BAR_FOO_H .

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