How to properly name include guards in c++

后端 未结 4 1510
忘掉有多难
忘掉有多难 2021-01-21 08:05

I have 3 header files:

misc.h
MyForm.h
Registration.h

In misc.h file I put

#ifndef MISC_H
#define MISC_H
#endif
4条回答
  •  醉梦人生
    2021-01-21 08:38

    How to name include guards is somewhat opinion based, but a few recommendations can be made:

    1) Don't make them short as they are then likely to clash with other macros defined in other files or the implementation or libraries you use.

    2) Make them contain a project specific prefix in an attempt to make them unique and unambiguous.

    3) If your project contains multiple sub-parts "modules"/"libraries" etc, make the guard name contain the name of the module to make them unique within your project - include the file name as well.

    4) Make sure not to use reserved names such as NULL, names starting with a number or names that begin with an underscore followed by an uppercase letter as well as names containing consecutive underscores; all such names are reserved for the implementation to use.

    5) Use all uppercase for macros (just a common convention).

    For a file named "baz.h" in a project named "foo", in submodule "bar", I'd name the guard FOO_BAR_BAZ_H.

    PS. Make sure all your headers use include guards (except in very special and rare cases). Otherwise you are inviting trouble with multiple definition errors and more.

提交回复
热议问题