Search code examples
functiongdbwatchinternal

GDB: Can I add a "watch" for a variable in another scope?


Seems that watch only works when I run into a function and watch the value of a function-local variable. My question is, can I watch and see if a function's input parameter is larger than a number? E.g. I've this code:

$cat testWatch.cpp
#include<stdio.h>
void f(int i){
    ++i;
    printf("%d\n",i);
}
int main(){
    int i=1;
    f(2);
    f(3);
    ++i;
    f(4);
    ++i;
    return 0;
}

I wish to

(1) When program is in "main" function, I wish to set a "watch" inside f(). Is it possible?

(2)I want set a "watch" point at the beginning of f() function, when the input "int i" is larger than 2, I want gdb to stop. Is it possible?


Solution

  • 1) do you really need a 'watch'? It's trivial to set a conditional breakpoint inside f() by specifying the line number. (or in less trivial programs, fileName:lineNum )

    2) the behavior you describe is a conditional breakpoint.

    (gdb) break 2 if (i > 2)
    Breakpoint 5 at 0x400531: file test.c, line 2.
    (gdb) run
    Starting program: /tmp/test
    3
    
    Breakpoint 5, f (i=3) at test.c:3