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 into GDB? ›

Run GDB by specifying the compiled program as an argument: gdb ./myprogram. Start the program within GDB using the run command, providing any desired command line arguments: run arg1 arg2. Set breakpoints within GDB to pause execution at specific locations in your program.

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 is GDB and how do you debug C and C++ code? ›

The program under debug might enter an infinite loop or a deadlock state. The debugger does not detect those automatically. You need to interrupt the execution (normally by pressing Ctrl-C) and debug as usual: examine variables, set breakpoints, single-step, whatever.

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? ›

Debugging C programs
  1. To compile the program, use: gcc -g -Wall *. c . ...
  2. Now enter gdb with the command gdb a. out .
  3. At the gdb prompt, enter run . ...
  4. You can enter where , and gdb will show the current stack of subroutine calls, and the line number for each. ...
  5. Type quit to exit gdb and return to the shell prompt.

How to run command with 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 to pass argument in command-line? ›

Note: You pass all the command line arguments separated by a space, but if the argument itself has a space, then you can pass such arguments by putting them inside double quotes “” or single quotes ”.

How do you access command-line arguments within the code? ›

Command line arguments in C are passed to the main function as argc and argv. Command line arguments are used to control the program from the outside. argv[argc] is a Null pointer. The name of the program is stored in argv[0], the first command-line parameter in argv[1], and the last argument in argv[n].

How to use GDB for beginners? ›

GDB - Commands
  1. b main - Puts a breakpoint at the beginning of the program.
  2. b - Puts a breakpoint at the current line.
  3. b N - Puts a breakpoint at line N.
  4. b +N - Puts a breakpoint N lines down from the current line.
  5. b fn - Puts a breakpoint at the beginning of function "fn"
  6. d N - Deletes breakpoint number N.

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

Is GDB a command line debugger? ›

GDB is started by typing gdb on the command line along with the name of the executable file to be debugged. If the program takes command line arguments, they are not given here. A splash message is displayed and then the GDB prompt is given, (gdb).

How to debug a process using GDB? ›

You can insert breakpoints; you can step and continue; you can modify storage. If you would rather the process continue running, you may use the continue command after attaching GDB to the process. When you have finished debugging the attached process, you can use the detach command to release it from GDB control.

What does GDB mean in debugging? ›

GDB stands for the “Gnu DeBugger.” This is a powerful source-level debugging package that lets you see what is going on inside your program. You can step through the code, set breakpoints, examine and change variables, and so on.

How to set breakpoint in GDB command line? ›

Setting breakpoints. Breakpoints are set with the break command (abbreviated b ). The debugger convenience variable `$bpnum' records the number of the breakpoint you've set most recently; see section Convenience variables, for a discussion of what you can do with convenience variables.

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

Once you have your launch configuration set, start your debug session with F5. 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 do you run a go command in debug mode? ›

To debug a program, execute the dlv debug command. Attach the filename at the end of this command, and debugging will start. For example, if you want to debug the main.go file, run the command dlv debug main.go . It is also known as “delve server” because this is a running process waiting for instructions.

References

Top Articles
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 5830

Rating: 4.8 / 5 (68 voted)

Reviews: 83% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.