Basic GDB

arun3sh

Arunesh Choudhary

Posted on May 10, 2023

Basic GDB

The GNU Debugger, also known as GDB, is an effective tool for debugging C and C++ programmes. It enables developers to find and resolve bugs and other problems by analysing and comprehending the behaviour of their code during execution.

The fundamentals of using GDB, such as setting breakpoints, looking at variables, and navigating programm execution, will be covered in this blog.

Setting breakpoints
Setting breakpoints in your code is the first step in utilising GDB. Breakpoints are places in the code when the program will halt execution so that you can inspect its behavior and state.

Use the break command, the name of the function or file, and the line number where you wish to place the breakpoint in GDB to create a breakpoint. For instance, you would run the following command to establish a breakpoint at line 10 of a file called my_program.cpp:

(gdb) break my_program.cpp:10
Enter fullscreen mode Exit fullscreen mode

Investigating variables
Using the print command once you've set a breakpoint, you can check the values of the variables in your programme. For instance, if you wanted to print the value of a variable called x, you would type the command:

(gdb) print x
Enter fullscreen mode Exit fullscreen mode

The watch command can also be used to keep an eye on a variable's value and halt the programme if it changes. You would type the following command to watch a variable called y:

(gdb) watch y
Enter fullscreen mode Exit fullscreen mode

Program navigation
You can use a number of GDB commands to browse programme execution once you've established breakpoints and looked at variables.

Use the run command to launch the programme and start running it. Use the step command to go through the programme line by line. Use the continue command to continue execution until the following breakpoint or watchpoint.

Additionally, you can go up and down the stack by using the up and down commands and the backtrace command, which displays a stack trace of the recent function calls.

Conclusion
GDB is an effective tool for debugging C and C++ programmes. Developers can obtain a better knowledge of the behaviour of their code and quickly find and fix problems by establishing breakpoints, looking at variables, and navigating programme execution.

Although some of the fundamental GDB commands and features have been discussed in this blog, there is still plenty to learn. For more complex usage, such as remote debugging, sophisticated breakpoints, and other features, the GDB documentation is a fantastic resource.

💖 💪 🙅 🚩
arun3sh
Arunesh Choudhary

Posted on May 10, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related