6

I wish to print the variable in a function (which is called multiple times ) to be printed each time the function is invoked.

Is it possible to do this automatically through gdb ?? Something like conditional printing ...

something like ..

void func()
{ 
    if( t == 0 ) 
       x = z+1;
    else
       x = p+2; 
} 

I want the variable to be printed when t == 0 and ignore otherwise ..

Jay
  • 24,173
  • 25
  • 93
  • 141
Onkar Mahajan
  • 944
  • 2
  • 13
  • 16
  • 1
    [This][1] is a nice GDB "cheat-sheet" (I've got a laminated double-sided copy at my side whenever I'm debugging), and [this][2] is a nice tutorial. [1]: http://www.tacc.utexas.edu/fileadmin/class_materials/gdb_refcard.pdf [2]: http://www.unknownroad.com/rtfm/gdbtut/gdbuse.html – William Nov 27 '10 at 04:09
  • 1
    The gdb refcard link is broken. It can be found on archive.org at http://web.archive.org/web/20100611221250/http://www.tacc.utexas.edu/fileadmin/class_materials/gdb_refcard.pdf – Cristián Romo Jul 08 '13 at 15:58
  • Subset without conditional part: http://stackoverflow.com/questions/6517423/do-specific-action-when-certain-breakpoint-hits-in-gdb – Ciro Santilli OurBigBook.com Apr 08 '16 at 12:38

3 Answers3

7

This can be done with a combination of the commands breakpoint, condition, and commands.

  1. Set a breakpoint with breakpoint func
  2. Make it conditional by condition t == 0
  3. Make the breakpoint print local variables with:

.

commands  
info locals  
end  

or specific variables with:

commands  
print t
print z
print x  
end  
wnoise
  • 9,764
  • 37
  • 47
3

Make a breakpoint at line x=z+1 , use 'command [breakpoint number] to print the variable and continue.

This works because you have branch in the code.

If there's not if-else branch. U can also use 'break if condition' and do the command thing.

wliao
  • 1,416
  • 11
  • 18
  • +1, and it could be easier to use `display` _expr_ as it will automatically have the value of _expr_ printed each time the breakpoint is reached. – William Nov 27 '10 at 04:06
0

you can actually break in a specific place on a condition.

e.g. break sourcefile.c:123 if x + y -foo(z) == 4. this will break on line 123 of sourcefile.c if that expression evaluates to true. Then you can print whatever value you want (or continue until the next time the condition is satisfied)

chacham15
  • 13,719
  • 26
  • 104
  • 207