Question

I read some answers about this topic, but I am still not sure:

In C++ a global const variable definition is automatically static. However I can access it from another cpp-file through extern:

// module.cpp

const int i = 0;

and

// main.cpp

extern const int i;

int main ()
{
    if (i > 10)
        return 0;
    else
        return 1;
}

Why is this possible (accessing an object with internal linkage from another module)? Normally I should be forced to define i as extern const int i = 0 in module.cpp, to have an explicitely global but non-static const, or?

In comparison, this is not possible:

// module.cpp

static int i = 0;

and

// main.cpp

extern int i;

int main ()
{
    i = 10; // but read-only access like (i > 10) would be possible!
    return 0;
}

So is the answer that: yes, you can access internal linked objects from other modules, but only for read (so always with const)?

Edit:

Sorry, but I made a mistake: in my original code I just tried an expression without effect (in both examples):

extern const int i; // or extern int i for second example
int main ()
{
    i>10;
    return 0;
}

I thought, that it behaves the same, as if program flow or data was dependent of this expression, but in fact it does not! The compiler seems to just cut out this effectless expression, so that the linker does not see it! So all is alright: in the first example i must be indeed defined extern const int i = 0 in module.cpp, and in the second example i cannot be accessed at all (unless in effectless expression). Compiler is VC++2010.

Edit2:

However, now I don't understand why this is possible:

// module.cpp

extern const int i = 0;

and

// main.cpp

int i = 99;

int main ()
{
    bool b = i>10;
    return 0;
}

i have both external linkage. But no error. When in module.cpp I define int i = 0, then error (multiple symbols). Why?

Was it helpful?

Solution

As for me it looks like a compiler bug. Constant variable i is not defined It is only declared in main.cpp. As for variable i in module.cpp then it has internal linkage and shall not be accessible outside the module.

Relative to your addition to the original post then the compiler has nothing common with this situation. It is linker that checks whether there are duplicate external symbols. I think it decided that if one variable has qualifier const and other has no it then there are two different variables. I think that it is implementation defined whether the linker will issue an error or not. Moreover it can have some options that could control the behaviour of the linker in such situations.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top