C++ #ifndef for include files, why is all caps used for the header file?

后端 未结 7 1832
猫巷女王i
猫巷女王i 2021-01-06 12:32

I wonder why the name after the #ifndef directive is always all caps and don\'t seem to match the name of the actual header file? What are the rules surrounding

7条回答
  •  感动是毒
    2021-01-06 12:52

    There's no "rule", there are just conventions. The first and most used convention is that all precompiler macros are all uppercase, so header guards too should be all uppercase.

    As for the macro name, what I use (and what most of the code I've seen uses) is just the name of the header (as said, turned to all uppercase) including extension, replacing the dot with an underscore, followed by _INCLUDED.

    #ifndef MYHEADER_HPP_INCLUDED
    #define MYHEADER_HPP_INCLUDED
    // ...
    #endif
    

    Note that many prepend such identifiers with an underscore or a double underscore, but it's not good practice, since the standard specifies that identifiers beginning (or containing) double underscores and those beginning with a single underscore followed by an uppercase letter are reserved for compiler/library-specific stuff (e.g. __declspec in VC++ or macros used in the standard headers) at all scopes; all the other identifiers beginning with a single underscore are reserved at the global scope. So such identifiers shouldn't be used to avoid collisions.

    More info on this stuff here.

提交回复
热议问题