Home > Software design >  extern "C" variables affected by compiler optimization level
extern "C" variables affected by compiler optimization level

Time:08-22

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.

CodePudding user response:

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.

  • Related