#ifndef why to use an other name than the class name?

1k views Asked by At

Classes declarations usually look like that:

#ifndef MY_CLASS_20141116
#define MY_CLASS_20141116

...

class MyClass
{
    ...
}

#endif

My question is, why to not use the class name instead of redefining a new identifier:

#ifndef MyClass

...

class MyClass
{
}

#endif

I guess it has something related with identifier conflicts (a same identifier may appear twice) or the use of namespace (I do not know if a full identifier like std::array may be used in the #ifndef directive).

It would be great a more thorough explanation.

Also, it is possible to use the second test when using namespace?

#ifndef A::MyClass //not compile, any equivalent?

namespace A
{
...

    class MyClass
    {
    }
}
#endif
1

There are 1 answers

1
Synxis On BEST ANSWER

First example:

#ifndef MyClass

...

class MyClass
{
}

#endif

This cannot work, because 'MyClass' is never defined for the preprocessor. All directive starting with a # are preprocessor directives and are the only ones the preprocessor understands. class MyClass has no special meaning for the preprocessor, and won't create a preprocessor definition.

For it to work, you have to define MyClass : #define MyClass. However, by doing this, the preprocessor will replace class MyClass by class, which won't compile.

Now, second example:

#ifndef A::MyClass //not compile, any equivalent?

A::MyClass is not a preprocessor token, it is several tokens. #define SOMETHING only work with one token (which is composed of the characters a-zA-Z_0-9).