Pages

Introduction to gdb

gdb stands for gnu debugger,a tool to debug programs of language C,C++ etc. It does not have gui and is a command line based debugger.

In this post we will learn how to start using the debugger to debuga simple C program.

First step is to install the debugger, you can do that from your pacakge manager by searching for the package by the name gdb.

Once you have installed gdb open the terminal and run the command

gdb --version

To make sure the installation has happened successfully. You should see an output similar to this.



Now to start debugging let us take an example program

ex_gdb.c



To be able to debug a C program we need to use the option "-g", so that the debugging realted information is incorporated into the executable.

Thus compile the above code as follows



Now to debug this code pass the executable to gdb as below



output:



At this gdb prompt, we can run various commands that will help us debug the code To come out of the prompt use the command quit.

The program is not executing as of now, to start the execution type "run" at the gdb prompt and hit enter. The program starts running and if no break points are set in the program, will run till the end.

To set a breakpoint before starting the execution use the command break for e.g. to set a breakpoint at the function main run the command



As you can see, the execution has halted as soon as the main function is encountered. Now we can single step through the code, executing the program line by line. To execute the next line of the code use the command "next"



You can see above the print statement was executed and its output shown on the screen, before starting the execution of the next statement. At exch step the statement that is going to be executed next is shown.

In case we want to view the value of variables we can use the command "print" and pass the variable name whose value we want to view. For eg. if we want to view the value of "var1" inside for loop in the above program we can do it as follows



As we can see the value of var2 is sbeing printed rightly as "0" after the execution of the statement "var2 = var2 *i" where i was 0.

To stop single stepping and execute the rest of code use the command "continue". The program will run till next break point or till the end of the code if there are no more break points.

No comments:

Post a Comment