Before you run gdb make sure to compile your code with the -g flag!
To start gdb simply type gdb followed by the path to the program
$ gdb ./some_path/my_test_program
$ gdb my_test_program
Alternatively you can connect to a running process by using the -pid flag followed by the process id of the running program (e.g. 183429)
$ gdb attach pid 183429
Once in gdb you can use the gdb terminal to interact with your program. Below are a list of commands you can use.
run or r -> starts the program and executes until: completion, an exception occurs, a break point is seen, or abnormal termination occurs
break or b -> creates a break point where the program will stop execution.
Options:
$ b 193 -> creates a new breakpoint at line 193
$ b main() -> creates a breakpoint at the beginning of function main
$ b 193 if <some condition> -> breaks at line 193 if <some condition> is true
next or n -> moves to the next line of the program
step or s -> moves to the next line of the program, if used on a function call gdb will attempt to move to the first line of the function
continue or c -> restarts execution until: completion, an exception occurs, a break point is seen, or abnormal termination occurs
quit or q -> quits gdb
print or p -> allows for printing to the terminal.
Example:
$ p my_var -> prints my_var to the console
$ p/x my_var -> prints my_var as hexadecimal
$ p/d my_var -> prints my_var as a decimal
$ p/c my_var -> prints my_var as a character
$ p/o my_var -> prints my_var in octal
$ p/u my_var -> prints my_var as unsigned decimal
$ p/t my_var -> prints my_var as binary
$ p/s my_var -> prints my_var as a string
list or l -> prints out the 10 lines beginning at the current location, successive commands will print the next lines available, you can also pass a line number to jump to a specific location (e.g. $ list 150)
info b -> lists all break points
del -> deletes all break/watch points, you can pass a specific number to delete a specific break point
disable <some break point> -> disables a specific watch/break point given by <some break point>
enable <some break point> -> enables a specific watch/break point given by <some break point>
watch <some address> -> gdb will watch a certain memory address for changes made there. When updates are made they will be displayed
The TUI functionality of gdb shows your source code and highlights the current line of code as you single step. Start TUI by typing ctrl+x ('ctrl' pressed together with 'x') followed by '1'. When you do this, the top half of your gdb window will be your source code and the bottom half is the gdb terminal.