Friday, February 25, 2011

Getting Started with GDB

GDB is a very powerful debugging tool for C/C++ and many other languages. Here I'm gonna show you how to get started with GDB.

testgdb.cpp
#include <iostream>
#include <string>
using namespace std;

string globalmsg = "Hello World";

void half(int& a) {
    a /= 2;
}

int whatever() {
    int i = 5;
    i *= 3;
    return i;
}

int main() {
    int a = 10;
    half(a);
    cout << a << endl;
    cout << whatever() << endl;
    return 0;
}

1. Compile the code
g++ -c -g -Wall -O0 testgdb.cpp
The -O0 flag is useful for debugging information because the compiler may do its own optimization that can eliminate some debugging information, such as -O2 flag for example.
2. Link it
g++ -o testgdb testgdb.o
3. Run it
gdb ./testgdb
After running this statement, there will be gdb prompt.
4. Set the breakpoint in line 18 and 19
break testgdb.cpp:18
break testgdb.cpp:19
5. See the list of breakpoints
info break
6. Remove the second breakpoint
delete 2
7. Run the program
run
8. See the current line
list
9. Step over to the next line
next
10. See the current line again
list
11. Step in to the half() function
step
12. Print the arguments
info args
13. Go to the next line
next
14. Print the value a now
print a
The new value should be 5.
15. Step out from half() function
finish
16. Print all the local variables
info locals
17. Set another breakpoint in line 13
break testgdb.cpp:13
18. Jump to that newly-set breakpoint
continue
19. Step over
next
20. Print the new value of i
print i
The value of i should be 15
21. Step out from the whatever() function
finish
22. Get the length of globalmessage string
print globalmessage.size()
23. Quit gdb
quit

I hope this brief introduction is useful. For more information, type
help <command>

No comments:

Post a Comment