Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extern "C" variables affected by compiler optimization level

Tags:

c++

gcc

Consider this link with the snippet

#include <cstdio>

namespace X {
    extern "C" int z;
}

namespace Y {
    extern "C" int z;
}

int X::z = 1;
int main()
{
    std::printf("%d -- %d\n", X::z, Y::z);
    X::z = 2;
    Y::z = 4;
    std::printf("%d -- %d\n", X::z, Y::z);
    X::z = 0;
    std::printf("%d -- %d\n", X::z, Y::z);
}

With -O1 GCC outputs

1 -- 1
2 -- 4
0 -- 0

whereas the output of GCC with no optimization enabled matches with that of CLANG (across all optimization levels) i.e.

1 -- 1
4 -- 4
0 -- 0

Is this a compiler bug in GCC because with extern "C" I'd expect name mangling to be disabled and thus there being only the variable z in both the namespaces and thus the values should always be the same.

like image 877
Zoso Avatar asked Jun 16 '26 21:06

Zoso


1 Answers

This is a GCC bug. A similar test case has already been reported here. (Although that one could be a bit more subtle than your test case because it also depends on how exactly using namespace lookup works).

As you are expecting the standard says that variable declarations with C linkage and the same name declared in different namespace scopes refer to the same entity, see [dcl.link]/7.

like image 182
user17732522 Avatar answered Jun 18 '26 11:06

user17732522



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!