Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

namespaces

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.

like image 639
BugRepairMan Avatar asked Dec 10 '22 14:12

BugRepairMan


1 Answers

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

like image 99
NathanOliver Avatar answered Jan 06 '23 19:01

NathanOliver