Why does "#define A" interfere with the "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; }

Error Information

error: overriding 'int {anonymous} :: i'

Once defined Aand Bwhy do namespace names become anonymous?

Used compiler: gcc-4.9.3.

+4
source share
1 answer

AT

#define A
#define B

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

You define Aand Blike nothing. That means your code will become

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

After starting the preprocessor. As both namespaces become anonymous namespaces, the compiler correctly complains that you are updating i.

, -, , .

#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;
}

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;
}

, , : GCC - C

+13

Source: https://habr.com/ru/post/1660795/


All Articles