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
The idea is to make sure your header file is only read once during build. The idiom to accomplish that is the structure:
#ifndef _SOME_UNIQUE_NAME
#define _SOME_UNIQUE_NAME
/* The actual header code */
#endif
This means that you should choose a name that you are pretty sure will be unique and is a valid identifier for #ifndef. You should also make sure that the identifier is not used in actual code or confused with a variable or something. Having an upper case tag marks the idiom clearly. Besides that, it is merely conventions not language that dictate that choice. Visual Studio's wizards generates a GUID like identifier for. Sone compilers support #pragma once that have the same effect.
You can use any name you want, but you want to make it unique so that value won't be defined outside your header by any chance, so using header name with uppercase is just a nice convention to ensure that.
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.
It's not required to be all caps. It's just the common convention. I usually use something like #ifndef MYHEADER_H_INCLUDED
.
Google for "include guard" to find what the thing is actually about.
About the all-caps: It's a convention for macros to be in all-upper-case. The reason is that macros are processed by the preprocessor, an arcane text processing tool, that knows nothing of C++, and is best shut out of common identifiers, lest it tramples all over them, creating a big mess.
These are preprocessor symbols and have no such rules. (as long as they match the #defines
in the headers)
However, convention is to use all-caps for preprocessor symbols.