1

I compile those code with Visual studio 2019 in win10

My project have just two source files:

/**** a.cpp  ****/

namespace pers{
    const int LEN = 5;
}
/**** b.cpp  ****/

namespace pers {
    const int LEN = 5;
}

int main() {
    return 0;
}

It can be compiled successfully.But I dont konw why? I defined LEN twice!!

so, I delete the const :

/**** a.cpp  ****/

namespace pers{
    int LEN = 5;
}
/**** b.cpp  ****/

namespace pers {
    int LEN = 5;
}

int main() {
    return 0;
}

Now it doesn't work!

So, my question is what happend? const variable in diffierent source files can be defined twice or more (means NO multi-definition error) .

Meanwhile, compiler will throw "multi-definition error" obviously if do this:

// those code in same cpp file.

namespace pers {
    const int LEN = 5;
    const int LEN = 5; // multi-definition error

    const int LEN2 = 10;
}
namespace pers {
    const int LEN2 = 10; // multi-definition error
}


int main() {
    const int a = 10;
    const int a = 10; // multi-definition error

    return 0;
}
rawrex
  • 4,044
  • 2
  • 8
  • 24
achange
  • 61
  • 3
  • Please, show how do you include code from the `a.cpp` into the `b.cpp`. My guess is that you do not have a header file for the namespace's interface which you include in files where the namespace is going to be used. – rawrex May 25 '22 at 03:45
  • @rawrex No header file, I just try your advice of adding a header file "a.h" as ``` #pragma once namespace pers { const int LEN = 10; } ``` then, I include "a.h" in "main.cpp" and print pers::LEN, it will always be 10. Code of a.cpp and b.cpp have no influence, but compile successfully. – achange May 25 '22 at 04:05

0 Answers0