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.cppThe -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.o3. Run it
gdb ./testgdbAfter running this statement, there will be gdb prompt.
4. Set the breakpoint in line 18 and 19
break testgdb.cpp:18
break testgdb.cpp:195. See the list of breakpoints
info break6. Remove the second breakpoint
delete 27. Run the program
run8. See the current line
list9. Step over to the next line
next10. See the current line again
list11. Step in to the half() function
step12. Print the arguments
info args13. Go to the next line
next14. Print the value a now
print aThe new value should be 5.
15. Step out from half() function
finish16. Print all the local variables
info locals17. Set another breakpoint in line 13
break testgdb.cpp:1318. Jump to that newly-set breakpoint
continue19. Step over
next20. Print the new value of i
print iThe value of i should be 15
21. Step out from the whatever() function
finish22. 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>