C Programming

How to Step Into or Over a Function in GDB

Debugging is a fundamental skill that any self-identified programmer should have. It allows us to view, review, and fix errors in our code. One powerful debugging tool is the GNU Debugger, GDB for short.

This guide will look at working with GDB to step into or over a function in our code.

Basic GDB Usage

To illustrate this, you can use your code or use the sample provided below. In the example below, the loop me function contains a loop that we will examine with GDB.

#include
void loopMe()
{
    for(int i=0;i<5;i++){
        printf("i is %d\n", i);
    }
}

int main() {
    int a = 10;
    a += 10;
    printf("Value of a is %d", a);
    loopMe();
    return 0;
}

Compile the code with -g as:

$ gcc -g loop.c -o loop

Next, launch the program with GDB as:

$ gdb loop

Once in GDB, we can run the program by using the run or r command. You can stop the program while it's running by using the CTRL + C key.

Let us set a breakpoint at the main function to halt the execution at that point. In the example above, we halt at line 10.

$ (gdb) break main

Breakpoint 1 at 0x555555555171: file loop.c, line 10.

To step through your program line by line, you can use the next or n command.

$ (gdb) next
$ (gdb) n

Once you get to the function you want to work on, in the example above, the loopMe() function, you can step over it using the next command.

This will skip function and go directly return 0 as:

You can also step into the function and work on it using the step or s command. For example, to enter the loopMe() function, we can do:

$ (gdb) step

The command will step into the function as:

Now that we are inside the loopMe() function, we can go through it line by line using the next command:

As you can see, we run through the loop and see how the loop executes.

Conclusion

In this quick tutorial, we discussed the process of using GDB to step over or into a function when debugging.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list