How to use gdb in Ubuntu Terminal

Here's a practical, minimal guide for using GDB in Ubuntu terminal — from launching to setting breakpoints and navigating your code.


๐Ÿงฐ Step 1: Compile with Debug Symbols

Use -g and disable optimizations (-O0 preferred for debugging):

bash
g++ -g -O0 -o myprog myprog.cpp

๐Ÿš€ Step 2: Launch GDB

bash
gdb ./myprog

You'll see a (gdb) prompt.


๐ŸŽฏ Step 3: Set Breakpoints

You can set breakpoints in three main ways:

✅ a. At a function

gdb
(gdb) break main

✅ b. At a specific file and line

gdb
(gdb) break myprog.cpp:42

✅ c. At a method in a class

gdb
(gdb) break MyClass::doSomething

If the symbol is mangled (C++), GDB usually demangles automatically, especially if compiled with -g.


▶️ Step 4: Run the Program

gdb
(gdb) run

๐Ÿงญ Step 5: Navigate

CommandMeaning
next or nStep over current line
step or sStep into function call
finishRun until current function returns
continue or cContinue until next breakpoint
listShow source code around current line
info localsShow all local variables
print xPrint variable x

⛏️ Step 6: Manage Breakpoints

List breakpoints:

gdb
(gdb) info breakpoints

Delete a breakpoint:

gdb
(gdb) delete <number>

Disable/Enable breakpoint temporarily:

gdb
(gdb) disable <number> (gdb) enable <number>

๐Ÿงช Example Session

bash
g++ -g -O0 -o test test.cpp gdb ./test
gdb
(gdb) break main (gdb) break test.cpp:18 (gdb) run (gdb) next (gdb) print myVar (gdb) continue

๐Ÿง  Pro Tips

  • Press <TAB> for autocompletion.

  • Use layout src in GDB to get a TUI (text UI).

  • quit to exit.


๐ŸชŸ Bonus: GDB Text UI Mode

In GDB:

gdb
(gdb) layout src

→ Shows source code window with current line highlighted. Use arrow keys or n, s, etc.


Let me know if you'd like:

  • Watchpoints (for memory change)

  • Debugging core dumps

  • Pretty printing with gdbinit

  • Automating GDB session with scripts

No comments:

Post a Comment

If you have any doubts, please let me know.

Various types of salts effect on health (discussion with gemenie)

Is  rock salt or bitnoon helps in digestion or just a airuvedic nuska This is for informational purposes only. For medical advice or diagnos...