views:

80

answers:

4

Is there a way to know whether a variable is defined, by looking at the executable.

Lets say I declare

int i;

in the main function. By compiling and linking I get an executable my_program.exe.

Now, by looking inside my_program.exe, can I say if it has an int eger variable i ?

+1  A: 

If you compile with debugging symbols (for example, gcc -g) you can then use your debugger to see pretty much everything.

Brian Roach
+3  A: 

Not unless you compile with debugging enabled.

Vicky
And as long as optimization is turned off. With optimization, some variables may not show up in the debug symbols because they get optimized away.
JayM
+2  A: 

As others said, debugging information will show it. More specifically, for ELF files:

readelf -w binary-name

will have an entry like:

<2><58>: Abbrev Number: 4 (DW_TAG_variable)
 <59>     DW_AT_name        : i 
 <5b>     DW_AT_decl_file   : 1 
 <5c>     DW_AT_decl_line   : 2 
 <5d>     DW_AT_type        : <73>  
 <61>     DW_AT_location    : 2 byte block: 91 6c   (DW_OP_fbreg: -20)

Without debugging information, locals don't retain their names. If the variable is a global, there will be a symbol that points to it:

objdump -t binary-name

0804a010 g     O .data  00000004              i

Type information is lost there, but you can see the size is 4

Michael Mrozek
A: 

Local variables could be eliminated by the compiler during optimization process, so the initial value of variables will be hard to find out even with debugging symbols. That is platform specific though.

Kirill V. Lyadvinsky