Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the linker emit an error in the code below?

I found the example below here. Clearly the comment in the snippet was wrong as the variable S::x is odr-used by the expression &S::x.

struct S { static const int x = 1; };
void f() { &S::x; } // discarded-value expression does not odr-use S::x
int main(){
    f();
}

See live example

I understand the compiler doesn't need to emit such an error because [basic.def.odr]/10 says "no diagnostic required". But why doesn't the linker emit an error about the undefined variable S::x, as it does in the code below?

#include<iostream>
struct S { static const int x = 1; } s;

int main() {
    std::cout << &s.x << '\n';
}  

See live example.

like image 266
João Afonso Avatar asked Nov 08 '22 06:11

João Afonso


1 Answers

But why doesn't the linker emit an error about the undefined variable S::x, as it does in the code below?

Because it is simply optimized out! An expression which result is never used and has no side effect will simply be ignored. And what was ignored must not be linked in. There is simply no code which reference the variable, also if the address of it was taken but then is not used.

As seen in your wandbox example, the compiler emits the correct diagnostic: "expression result unused".

Code which is not in use will not result later in linker errors ;)

Your second example uses the value ( address of var ) and so there is a need to evaluate the expression. That emits code to the linker where the symbol of the address can not be found anywhere.

like image 91
Klaus Avatar answered Nov 14 '22 20:11

Klaus