Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC extension __attribute__ ((unused)) for variable attributes

following is a sample code for GCC variable attribute extension,

#include<stdio.h>
int main(void){
        int sam __attribute__((unused))= 10;
        int p = sam+1;
        printf("\n%d" , p);
}

for the assembly code of above program generated using:

gcc -S sample.c

the .s file dosen't contain the variable sam in it,whereas the output of program is "11" which is correct. So does the compiler neglect completely the unused variable and not output it in the executable? If so why is the output of program correct?Can anyone explain the working of unused and used variable attributes in gcc.

Thanks

like image 865
Sameeran Joshi Avatar asked Oct 31 '25 00:10

Sameeran Joshi


1 Answers

So does the compiler neglect completely the unused variable

Depends what you mean by "neglect". The compiler optimizes the code, but doesn't completely ignore the variable, as otherwise compiler couldn't calculate the result.

not output it in the executable?

Yes.

If so why is the output of program correct?

Because this is what a compiler does - generates programs with the output as described by the programming language. Code is not 1:1 to assembly, code is a language that describes the behavior of a program. Theoretically, as long as the output of the compiled program is correct with what is in the source code, compiler can generate any assembly instructions it wants.

You may want to research the terms side effect and the as-if rule in the context of C programming language.

Can anyone explain the working of unused and used variable attributes in gcc.

There is no better explanation then in GCC documentation about Variable Attributes:

unused

This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC does not produce a warning for this variable.

used

This attribute, attached to a variable with static storage, means that the variable must be emitted even if it appears that the variable is not referenced.

When applied to a static data member of a C++ class template, the attribute also means that the member is instantiated if the class itself is instantiated.

The attribute unused is to silence the compiler warning from -Wunused-* warnings.

The attribute used is meant to be used on variables (but I think works also on functions) so that the variable is generated to the assembly code. even if it is not unused anywhere.

like image 171
KamilCuk Avatar answered Nov 01 '25 21:11

KamilCuk



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!