charmae
charmae

Reputation: 1080

GDB unused variable

Is it possible to get the value of unused variable using GDB? Is there some configuration for GCC so that the garbage value of the unused variable will be shown not 'optimized out'?

c file:

#include<stdio.h>

void main()
{
    int x;
    int y;
    printf("value of x: %d",x);

}

In the gdb I want to get the garbage value of variable y.

(gdb) run
Starting program: /home/charmae/workspace/AVT/a.out 

Breakpoint 1, main () at file4.c:7
7       printf("value of x: %d",x);
(gdb) info locals
x = 2789364
(gdb) p y
$1 = <optimized out>
(gdb) p x
$2 = 2789364

Upvotes: 6

Views: 479

Answers (3)

gby
gby

Reputation: 15218

It has nothing to do with GDB. The entity that optimized that variable out is the compiler (probably GCC in your case). You might force it to keep it by declaring the variable as volatile

A better question is - why are you trying to do?

Upvotes: 1

You might add an y=y; statement. That would force y to be used, and with gcc -O0 -g keep track of it (at least on my Linux/Debian/Sid/AMD64 with gcc 4.6.2 and gdb 7.3.50)

Upvotes: 0

bmargulies
bmargulies

Reputation: 99993

It's nothing to do with gcc. Either the compiler has compiled code to maintain the value, or it hasn't.

Upvotes: 0

Related Questions