Tutorial on How to Use the GDB Debugger Easily (2024)

GNU or GDB debugger is an application for finding out how your C or C++ program runs or for analyzing the moment the program crashes. You can perform many useful tasks with GDB: run the program, stop the program under specific conditions, analyze the situation, make modifications, and test new changes.

Contents

  • 1. More on the GDB debugger
  • 2. Preparing the GDB debugger for use
  • 3. Setting breakpoints to stop the execution of a program
  • 4. Running the program slowly
  • 5. Printing values of variables and expressions
  • 6. Using where and frame commands
  • 7. Commands to use in the GDB debugger
  • 8. Other C++ debuggers to consider

More on the GDB debugger

You can use GDB as a C++ debugger if a program is written with the GNU compiler and the -g flag. By debugging with GDB, you can catch errors and solve them before they cause severe issues.

Tip: a quick option is using the onlineGDB debugger, which lets you compile and analyze C++ code online without having to download the debugger to your operating system.

Here is how the onlineGDB debugger looks:

Tutorial on How to Use the GDB Debugger Easily (1)

Preparing the GDB debugger for use

The first step of learning how to use GDB for C++ debugging is to compile the C++ code with the -g flag:

$ g++ - g filename.cpp

The next step is calling the GDB to start the debugging process for the program you wish to analyze:

$ gdb program_name

Note: for the next functions, the (gdb) part of the command appears automatically.

The code above opens this C++ debugger but does not run the program. There are several ways of running the program you have opened. First, you can execute it with run command:

$ (gdb) run

You can pass arguments if the program needs some command-line arguments to be passed to it:

$ (gdb) run arg1 arg2

Debugging with GDB lets you investigate the core file as well. The core file contains information about when a program crashed.

$ (gdb) core filename

Note: by typing the help command, you will learn more about the commands to use in the GDB debugger.

Setting breakpoints to stop the execution of a program

You can debug your C++ program more efficiently if you use breakpoints. Breakpoints refer to instructions that stop the execution at specific moments. For instance, you should set breakpoints in places you suspect to be problematic.

It is possible to set breakpoints in two ways:

  • Setting a line at which execution stops.
  • Setting a function name to stop execution at.

Note: it is a common practice to set breakpoints before running the program.

The following example sets a breakpoint at the start of the main function:

$ (gdb) b main

This example sets a breakpoint at a specific line (20):

$ (gdb) b 20

This example adds a breakpoint at the beginning of a class member function:

$ (gdb) b list::erase

This example lists all of the breakpoints:

$ (gdb) info b

The following example deletes a breakpoint at line 20:

$ (gdb) delete 20

Note: the GDB debugger accepts abbreviations of commands. Therefore, you can use b instead of break or p instead of print.

Running the program slowly

You might need to execute a program slowly, moving from one function to another. There are two ways of making the program run step-by-step.

next executes the current command, stops, and displays the next function in line for execution.

$ (gdb) next

step: executes the current command. In cases when it is a function call, it breaks at the beginning of that method. You can use it for looking for errors in nested code.

$ (gdb) step

Tutorial on How to Use the GDB Debugger Easily (2)

Pros

  • Easy to use with a learn-by-doing approach
  • Offers quality content
  • Gamified in-browser coding experience
  • The price matches the quality
  • Suitable for learners ranging from beginner to advanced

Main Features

  • Free certificates of completion
  • Focused on data science skills
  • Flexible learning timetable

GET 25% OFF

Tutorial on How to Use the GDB Debugger Easily (3)

Pros

  • Simplistic design (no unnecessary information)
  • High-quality courses (even the free ones)
  • Variety of features

Main Features

  • Nanodegree programs
  • Suitable for enterprises
  • Paid Certificates of completion

UP TO 70% OFF

Tutorial on How to Use the GDB Debugger Easily (4)

Pros

  • A wide range of learning programs
  • University-level courses
  • Easy to navigate
  • Verified certificates
  • Free learning track available

Main Features

  • University-level courses
  • Suitable for enterprises
  • Verified certificates of completion

FREE COURSES

Printing values of variables and expressions

With the GDB debugger, you can check the values of variables during specific moments of the execution. You will use the print command for this task. It is possible to print more complicated expressions, type casts, call functions, etc.

$ (gdb) print <expression>

The possible syntax for using print:

  • print <exp>: to get values of expressions.
  • print /x <exp>: to get the value of expressions in hexadecimal.
  • print /t <exp>: to get the value of expressions in binary.
  • print /d <exp>: to get the value of expressions as unsigned int format.
  • print /c <exp>: to get the value of expressions as signed int format.

Using where and frame commands

During analysis of code, you might need to check which function currently runs.

$ (gdb) where

By typing the where command, you will learn these things:

  • The name of the currently running function.
  • The name of the file in which the function runs.
  • The number of the line in which the function is.
  • The name of the function that called the current function.
  • The arguments the current function had.
  • If it is a call chain, you will see all of them.

You can analyze the values of variables local to the calling function (or other function in the stack). The frame command instructs the GDB debugger to work on the specific stack frame or the one you are currently at.

$ (gdb) frame

Tip: the stack frame shows the sequence of function calls.

  • frame <frame-num>: sets the current stack frame to the indicated as <frame-num>.
  • info frame: displays the state of the current stack frame.

Commands to use in the GDB debugger

CommandDescription
helpProvides information about a topic or commands you can use
fileIndicates which file to debug
runExecutes the program under GDB
breakAdds breakpoints to stop the program execution temporary
deleteDeletes breakpoints
clearDeletes breakpoints for a specific function
continueResets the program after a breakpoint triggers
stepRuns the current source line and stops before executing the next one
nextRuns the current source line. However, if the line is a function call, the debugger will fully execute the function before the execution stops again
untilRuns the current source line. If you are at the beginning of a loop, the debugger runs until the loop ends
listPrints a certain list from the source code
printPrints values of certain expressions

Other C++ debuggers to consider

  • Visual Studio has an integrated C++ debugger that lets you analyze code on the most popular operating systems such as Linux, Windows, macOS.
  • LLDB debugger is a modern debugger that has reusable components that employ libraries from LLVM.
  • WinDbg is a debugger for the Microsoft Windows operating systems.
Tutorial on How to Use the GDB Debugger Easily (2024)

FAQs

How do I use GDB debugger? ›

Let's learn by doing: –
  1. Start GDB. Go to your Linux command prompt and type “gdb”. ...
  2. Compile the code. Below is a program that shows undefined behavior when compiled using C99. ...
  3. Run GDB with the generated executable. ...
  4. Display the code. ...
  5. Set a breakpoint. ...
  6. View breakpoints. ...
  7. Disable a breakpoint. ...
  8. Re-enable a disabled breakpoint.
Jul 12, 2024

How to debug C program using GDB in 6 simple steps? ›

How to Debug C Program using gdb in 6 Simple Steps
  1. Write a sample C program with errors for debugging purpose. ...
  2. Compile the C program with debugging option -g. ...
  3. Launch gdb. ...
  4. Set up a break point inside C program. ...
  5. Execute the C program in gdb debugger. ...
  6. Printing the variable values inside gdb debugger.
Sep 28, 2018

How do you go step by step in GDB? ›

To execute one line of code, type "step" or "s". If the line to be executed is a function call, gdb will step into that function and start executing its code one line at a time. If you want to execute the entire function with one keypress, type "next" or "n".

How to use GDB to debug a running process? ›

To attach GDB to a program already running as a process:
  1. Find the process id (pid) with the ps command: $ ps -C program -o pid h pid. ps -C program -o pid h. Replace program with a file name or path to the program.
  2. Attach GDB to this process: $ gdb program -p pid. gdb program -p pid.

What is the step command in debugger? ›

The STEP command causes Debug Tool to dynamically step through a program, executing one or more program statements. In full-screen mode, it provides animated execution. STEP ends if one or more of the following conditions is reached: User attention interrupt.

What are the 7 debug steps? ›

Process of Debugging
  • Step 1: Reproduce the Bug. To start, you need to recreate the conditions that caused the bug. ...
  • Step 2: Locate the Bug. Next, find where the bug is in your code. ...
  • Step 3: Identify the Root Cause. Now, figure out why the bug happened. ...
  • Step 4: Fix the Bug. ...
  • Step 5: Test the Fix. ...
  • Step 6: Document the Process.
Jun 13, 2024

How do you debug step by step? ›

The five steps of debugging
  1. Step One: Gather information about the error.
  2. Step Two: Isolate the error.
  3. Step Three: Identify the error.
  4. Step Four: Determine how to fix the error.
  5. Step Five: Apply and test.
Jan 25, 2023

How to do remote debugging in GDB? ›

To start remote debugging, run GDB on the host machine, and specify as an executable file the program that is running in the remote machine. This tells GDB how to find your program's symbols and the contents of its pure text. Start GDB on the host, and connect to the target (see section Connecting to a remote target).

How do you start a program using GDB? ›

Starting your program. Use the run command to start your program under GDB. You must first specify the program name (except on VxWorks) with an argument to GDB (see section Getting In and Out of GDB), or by using the file or exec-file command (see section Commands to specify files).

How do I navigate GDB? ›

GDB - Navigating your program
  1. step. Execute the next statement. ...
  2. next. Execute the next statement. ...
  3. continue. Contine the execution of the program until it reaches a breakpoint, a fatal error or finishes execution normally. ...
  4. where. Print out the function call stack including the current line number. ...
  5. list.

How to list breakpoints in GDB? ›

You can see these breakpoints with the GDB maintenance command `maint info breakpoints' . Using the same format as `info breakpoints' , display both the breakpoints you've set explicitly, and those GDB is using for internal purposes. Internal breakpoints are shown with negative breakpoint numbers.

How does GDB work? ›

Gdb is a debugger for C (and C++). It allows you to do things like run the program up to a certain point then stop and print out the values of certain variables at that point, or step through the program one line at a time and print out the values of each variable after executing each line.

How to debug crash using GDB? ›

First, we want to find the line that it crashed on. There should now be a file called core inside the current directory (if not, see the Core Dump Settings section). Start a GDB session for the core dump. Immediately, GDB will output the line it crashed on.

How do I run a debugger code? ›

To bring up the Run and Debug view, select the Run and Debug icon in the Activity Bar on the side of VS Code. You can also use the keyboard shortcut Ctrl+Shift+D. The Run and Debug view displays all information related to running and debugging and has a top bar with debugging commands and configuration settings.

How to debug with GDB vscode? ›

Open the Run and Debug menu (Ctrl+Shift+D). Within the Run and Debug menu, select create a launch. json file . Then select Add Configuration , it should open a launch.

References

Top Articles
Abschlussarbeiten - Universität Bremen
In Brazil, the climate crisis is already turning working people into climate refugees
Global Foods Trading GmbH, Biebesheim a. Rhein
English Bulldog Puppies For Sale Under 1000 In Florida
Ets Lake Fork Fishing Report
Napa Autocare Locator
Plaza Nails Clifton
Vaya Timeclock
Guardians Of The Galaxy Showtimes Near Athol Cinemas 8
Kagtwt
Our History | Lilly Grove Missionary Baptist Church - Houston, TX
Saw X | Rotten Tomatoes
2024 Non-Homestead Millage - Clarkston Community Schools
Gma Deals And Steals Today 2022
Scenes from Paradise: Where to Visit Filming Locations Around the World - Paradise
Haunted Mansion Showtimes Near Millstone 14
Echat Fr Review Pc Retailer In Qatar Prestige Pc Providers – Alpha Marine Group
Hocus Pocus Showtimes Near Amstar Cinema 16 - Macon
Divina Rapsing
Where to Find Scavs in Customs in Escape from Tarkov
Account Suspended
Forest Biome
Somewhere In Queens Showtimes Near The Maple Theater
Used Safari Condo Alto R1723 For Sale
Brazos Valley Busted Newspaper
Putin advierte que si se permite a Ucrania usar misiles de largo alcance, los países de la OTAN estarán en guerra con Rusia - BBC News Mundo
Craigs List Tallahassee
Yugen Manga Jinx Cap 19
Suspiciouswetspot
Geico Car Insurance Review 2024
Star Wars Armada Wikia
Best Town Hall 11
Healthy Kaiserpermanente Org Sign On
Past Weather by Zip Code - Data Table
Craigslist Cars And Trucks Mcallen
Emiri's Adventures
Eaccess Kankakee
The Menu Showtimes Near Amc Classic Pekin 14
24 slang words teens and Gen Zers are using in 2020, and what they really mean
Compress PDF - quick, online, free
The Land Book 9 Release Date 2023
American Bully Xxl Black Panther
Sinai Sdn 2023
Überblick zum Barotrauma - Überblick zum Barotrauma - MSD Manual Profi-Ausgabe
Vintage Stock Edmond Ok
Southwest Airlines Departures Atlanta
Alba Baptista Bikini, Ethnicity, Marriage, Wedding, Father, Shower, Nazi
Gw2 Support Specter
Caesars Rewards Loyalty Program Review [Previously Total Rewards]
Graduation Requirements
Craigslist Marshfield Mo
Latest Posts
Article information

Author: Gregorio Kreiger

Last Updated:

Views: 6201

Rating: 4.7 / 5 (77 voted)

Reviews: 84% of readers found this page helpful

Author information

Name: Gregorio Kreiger

Birthday: 1994-12-18

Address: 89212 Tracey Ramp, Sunside, MT 08453-0951

Phone: +9014805370218

Job: Customer Designer

Hobby: Mountain biking, Orienteering, Hiking, Sewing, Backpacking, Mushroom hunting, Backpacking

Introduction: My name is Gregorio Kreiger, I am a tender, brainy, enthusiastic, combative, agreeable, gentle, gentle person who loves writing and wants to share my knowledge and understanding with you.