Names used for include guards?

孤者浪人 提交于 2020-05-23 21:10:12

问题


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 differ from the name used in the include guard. For example, I have seen sphere.h and then #ifndef SPHERE_H_. Could I just as easily have used SPHERE_ or do the names have to match? Are the underscores also necessary?


回答1:


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 .




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/50355923/names-used-for-include-guards

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!