BugRepairMan BugRepairMan - 18 days ago 4
C++ Question

Why does "#define A" interfere with "namespace A{}"?

The following code can compile:

namespace A{
int i;
}
namespace B{
int i;
}
int main(){ return 0; }


But the following code cannot compile:

#define A
#define B

namespace A{
int i;
}
namespace B{
int i;
}
int main(){ return 0; }


The error info is


error: redefinition of 'int {anonymous}::i'


After I define
A
and
B
why do the names of namespaces become anonymous?

The used compiler: gcc-4.9.3.

Answer

In

#define A
#define B

namespace A{
    int i;
}
namespace B{
    int i;
}

You define A and B to be nothing. That means your code becomes

namespace {
    int i;
}
namespace {
    int i;
}

After the preprocessor runs. Since both namespaces become anonymous namespaces the compiler correctly complains that you are redeclaring i.

Remember that when you define something the preprocessor is going to do through your source code and replace all occurrences of that symbol with whatever you defined it to be. Had you done

#define A LONG_NAME_I_DO_NOT_WANT_TO_TYPE
#define B ANOTHER_LONG_NAME_THAT_I_ALSO_DO_NOT_WANT_TO_TYPE

namespace A{
    int i;
}
namespace B{
    int i;
}

Then the preprocessor would change the code to be

namespace LONG_NAME_I_DO_NOT_WANT_TO_TYPE{
    int i;
}
namespace ANOTHER_LONG_NAME_THAT_I_ALSO_DO_NOT_WANT_TO_TYPE{
    int i;
}

For more information on how the preprocessor works see: GCC - The C Preprocessor

Comments