This repository provides a comprehensive reference for using GCC (GNU Compiler Collection) and GDB (GNU Debugger) for compiling and debugging C programs.
- Compile a C program:
gcc main.c -o program
- Enable debugging information:
gcc -g main.c -o program
- Enable warnings during compilation:
gcc -Wall main.c -o program
- Treat warnings as errors:
gcc -Werror main.c -o program
- Start GDB with a Text User Interface (TUI):
gdb --tui
- View source code:
list
- View the type of a variable:
whatis <variable>
- View members of a struct variable:
ptype <variable>
- Dereference a pointer:
* <pointer_name>
- Set a temporary breakpoint:
tbreak
- List all breakpoints:
info breakpoints
- Delete a breakpoint:
delete <breakpoint_num>
- Redirect GDB output:
tty <path>
- Set a conditional breakpoint:
b <file_name>:<line_number> if <condition>
- Jump directly to execution:
advance <function_name or filename:line_num>
- Execute until a specific line:
until <function_name or filename:line_num>
- Watch a variable for changes:
watch <variable_name>
- Enable/disable a breakpoint:
enable <breakpoint_num> disable <breakpoint_num>
- Save breakpoints to a file:
save breakpoints <file_name.txt>
- Load breakpoints from a file:
source <file_name.txt>
- Display changes in a variable:
display <variable_name>
- View list of displayed variables:
info display
- Remove a variable from display list:
undisplay <display_num>
- Backtrace to see the call stack:
bt
- Finish the current stack frame:
finish
- Navigate up/down in the call stack:
up down
-
Segmentation fault: Occurs when a program accesses memory it does not own.
-
Stack overflow: Happens when there is excessive memory usage in the call stack.
Get help for a specific command: ```bash help
-
Delta debugging: Use multiple breakpoints to isolate errors.
-
Calling functions within GDB:
call <function_name(arg...)>
-
Attaching GDB to a running process:
#Get process ID: ps aux | grep <name> #Attach to a process: gdb -p <process_id> #Detach from a process: detach
-
Handling core dumps:
#Set unlimited core dump size: sudo ulimit -c unlimited #Check core dump size: ulimit -c #Install necessary packages sudo apt install systemd-coredump #View core dump files coredumpctl dump coredumpctl gdb
- Set commands to execute automatically at breakpoints:
commands <breakpoint_num> print <variable> bt end
-
Create a script for GDB commands:
File name: .gdbinit Add commands inside the file.
-
Set a variable value:
set var <variable_name> = <value>
-
Reverse Debugging:
target record-full reverse-next
-
Debugging multithreaded programs:
- View Threads:
info threads
- Switch to a specific thread:
thread <thread_num>
- View Threads: