C++ Debugging - How To Use GDB [Code + Command Line Walkthrough] (2024)

Introduction - Debugging?

Debugging is necessary for any program of any size. It's inevitable that our code will return incorrect results, and we'll want to know what values are along the way to see where things are going wrong. For Linux, "gdb" (GNU Debugger) is one tool used for debugging C and C++ code. It can be used for larger programs, but we're going to keep things simple in this tutorial by showing how to use gdp with basic commands, for a simple program.

Installation

We'll assume that you're running Ubuntu 16.04 for this gdb installation, but the requirements are very basic. (We'll also assume that you have GCC installed to compile our C++ programs.

Run the following command in your terminal to install gdb and necessary dependencies:

sudo apt-get install libc6-dbg gdb valgrind 

And that's it.

A Basic C++ Program (With Some Bugs)

We're going to create a basic C++ program, and it's going to have a few bugs. We'll need to go through the code (with a debugger) to see why we aren't getting the expected result.

First of all, in your project directory, use the the following commands to create a makefile and our cpp file.

touch main.cpptouch makefile

Open "makefile" and add the following code to it:

1234567
all: g++ main.cpp -g -o run ./runcompile: g++ main.cpp -g -o runrun: ./run

(If you don't know about makefiles, look at this quick tutorial.)

Notice the extra -g flag for our compile command. This will tell the compiler to leave our code intact in the executable for debugging.

Our C++ program will ask the user for a number, and will calculate the factorial of that number.

​Open "main.cpp" and add the following code to it.

 1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930313233
// Copyright srcmake.com 2018.// A simple C++ with a bug or two in it.#include <iostream>using namespace std;int main() { // A factorial program to calculate n!. cout << "Enter a number, and we'll calculate the factorial of it.\n"; cout << "Number: "; int n; cin >> n; // The result of n!. Holds the running product of multiplying 1 to n. int factorial; // Go through each number from 1 to n. for(int i = 1; i < n; i++) { factorial = factorial * i; } // Output the result. cout << n << "! is " << factorial << ".\n"; /* Two noteable bugs: 1. "factorial" is never initialized. 2. "factorial" is muliplied from 1 to (n-1). It's not multiplied by n. */ return 0; }

Our code is complete.

​In your terminal, run "make" to test the code out.

make

Obviously, the answer our program outputs is wrong. Why is it wrong? Well, we could inspect the code to find out, but we could also use gdb to see what's happening in our code.

C++ Debugging - How To Use GDB [Code + Command Line Walkthrough] (1)

Using gdb to Debug The Program

We're going to use gdb to debug our program. Let's go through the commands that we need.

First of all, start gdb. (This still start a gdb shell session.)

gdb

​Next, we're going to tell gdb that our executable file (named "run") is the one we want to debug.

file run

Now we're going to set a breakpoint at main. (A breakpoint is basically where we tell our code "stop here so we can look at it".)

break main

Next, we start the program (executable) to see what's going on in the code.

run

We're going to say "next" (or "n") to go through the code line by line (as it's executed, not necessarily as it's written. For example, for loops will be called a lot).

next

At any time, to see the value of a variable, you can use "p variablename".

p factorial

This whole process will look something like this.

C++ Debugging - How To Use GDB [Code + Command Line Walkthrough] (2)

To quit out of the gdb shell sessions.

quit

And that's it. Use gdb to find out what's going on in your code.

Conclusion

In this tutorial, we had a simple C++ program, with a few bugs. To find out what was going on in our code, we used gdb to go through the code line by line to see what the values of variables were and how the code was executing.

We did a basic tutorial, but gdb can be used for much larger examples. To proceed further, familiarize yourself with all of the gdb commands, and use them as you need to for your own program.

Like this content and want more? Feel free tolook around and find another blog post that interests you. You can also contact me through one of the various social media channels.

Twitter:@srcmake
Discord:srcmake#3644
Youtube:srcmake
Twitch:www.twitch.tv/srcmake
​Github:srcmake

C++ Debugging - How To Use GDB [Code + Command Line Walkthrough] (2024)

FAQs

How to debug using GDB command line? ›

Debugging a program that produces a core dump
  1. Compile the program using the following command. g++ testit.c g o testit.
  2. Run it normally, you should get the following result: ...
  3. The core dump generates a file called corewhich can be used for debugging. ...
  4. As we can see from the output above, the core dump was produced.

How to pass command line arguments using GDB? ›

Passing command line arguments to GDB
  1. Overview:
  2. Step 1: Creating a program to debug.
  3. Step 2: Compiling the program with -g flag.
  4. Step 3: Start GDB with Command Line Arguments.
  5. Step 4: Passing the arguments.
  6. Step 5: Setting the breakpoint.
  7. Step 6: Start debugging the program.
  8. Step 7: Quit GDB.
Dec 6, 2023

How to use GDB to step through code? ›

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".

What command in GDB allows me to walk through the code line by line but not go into functions? ›

Useful GDB commands:
CommandDescription
next or nExecutes the next line of code without diving into functions.
stepGoes to the next instruction, diving into the function.
list or lDisplays the code.
print or pDisplays the value of a variable.
7 more rows
Jul 12, 2024

How to debug using command line? ›

To debug applications on a running correlator, run the following command: engine_debug [ [ global-options ] [command [options]] ... ] To obtain a usage message, run the command with the help option. Sending events to the correlator continues to put events on the input queue of each public context.

How to debug C code in command line? ›

Via the command line

To compile the program, use: gcc -g -Wall *. c . (The -g option is important: It tells gcc to include debugging information in a. out, which gdb will use to know which line the program is in.)

How do you navigate code in the debugger using step commands? ›

Navigate code in the debugger using step commands

To start your app with the debugger attached, press F11 (Debug > Step Into). F11 is the Step Into command and advances the app execution one statement at a time.

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 to set commands in GDB? ›

To create a user-defined command, we use the GDB command define , and give it a command name, which in our example is bugreport followed by a set of GDB commands that you want to execute or capture the output from.

How to debug C code line by line? ›

Steps for Interactively Debugging a C Program

Start debugging: Begin program execution by typing run or start in gdb. The program will run until it hits the first breakpoint or encounters an error. Step through the program: You can navigate through your program line by line using step commands.

How do you go line by line in debug mode? ›

Click the Debug | Step Into menu item or press the F11 key to step into any property or method for debugging. You can then continue the line by line execution by pressing F10 or continue ...

What is the difference between step and Stepi in GDB? ›

Use the step command to execute a line of source code. When the line being stepped contains a function call, the step command steps into the function and stops at the first executable statement. Use the stepi command to step into the next machine instruction.

How do I run debug from command line in Vscode? ›

Alternatively, you can run your configuration through the Command Palette (Ctrl+Shift+P) by filtering on Debug: Select and Start Debugging or typing 'debug ' and selecting the configuration you want to debug.

How to debug C file using GDB? ›

Debugging a C Program with GDB
  1. STEP 1: Building the executables. sample. c is a C file in spiking folder. Run the below commands to compile sample. ...
  2. STEP 2: Debugging. If you face any error while execution, Please refer FAQ section. TERMINAL 1: To debug sample. elf program, Open a new terminal and move to spiking folder.

How to run a command in GDB? ›

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 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).

References

Top Articles
How to watch free movies online: The 12 best websites for streaming
Sflix Alternatives: Best Sites to Watch Movies Online
Evil Dead Rise Review - IGN
Ucsf Ilab
159R Bus Schedule Pdf
Hotels Near Okun Fieldhouse Shawnee Ks
Provider Connect Milwaukee
80 For Brady Showtimes Near Cinemark At Harlingen
Academic Calendar Biola
Castle Nail Spa (Plano)
What Was D-Day Weegy
What Is Opm1 Treas 310 Deposit
Dusk Hypixel Skyblock
Best Pedicure Nearby
Dealer 360 Login Generac
Nearest Walmart Address
1v1 lol unblocked Game- Play Unblocked Game Online for Free!
Craigslist Ct Pets
Spaghetti Models | Cyclocane
Fgo Spirit Root
Costco Gas Price City Of Industry
2503 South Tacoma Way
Fishweather
Master Series Snap On Tool Box
Emerge Ortho Kronos
Dumb Money Showtimes Near Showcase Cinema De Lux Legacy Place
1773X To
Papa Johns Mear Me
Fort Worth Craiglist
Saint Lukes Epulse
Pokio.io
Visit.lasd
Ludwig Nutsac
Rage Room Longmont
Planet Zoo Obstructed
Babbychula
How to Watch Age-Restricted YouTube Videos Without Signing In
Chets Rental Chesterfield
Dinar Guru Recaps Updates
L898 Pill Blue Capsule
Every Act That's Auditioned for AGT Season 18 So Far
Used Cars for Sale in Phoenix, AZ (with Photos)
Zuercher Portal Inmates Kershaw County
Mosley Lane Candles
Pinellas Fire Active Calls
Kayky Fifa 22 Potential
Epaper Dunya
Netspar on LinkedIn: Netspar is pleased to announce the next Netspar Pension Day, which will…
Fayetteville Arkansas Craigslist
Swag Codes: The Ultimate Guide to Boosting Your Swagbucks Earnings - Ricky Spears
Sky Zone Hours Omaha
Dominos Nijmegen Daalseweg
Latest Posts
Article information

Author: Msgr. Refugio Daniel

Last Updated:

Views: 6195

Rating: 4.3 / 5 (74 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Msgr. Refugio Daniel

Birthday: 1999-09-15

Address: 8416 Beatty Center, Derekfort, VA 72092-0500

Phone: +6838967160603

Job: Mining Executive

Hobby: Woodworking, Knitting, Fishing, Coffee roasting, Kayaking, Horseback riding, Kite flying

Introduction: My name is Msgr. Refugio Daniel, I am a fine, precious, encouraging, calm, glamorous, vivacious, friendly person who loves writing and wants to share my knowledge and understanding with you.