Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Shell Scripting
  • Kali Linux
  • Ubuntu
  • Red Hat
  • CentOS
  • Docker in Linux
  • Kubernetes in Linux
  • Linux interview question
  • Python
  • R
  • Java
  • C
  • C++
  • JavaScript
  • DSA
Open In App

gdb command in Linux with examples

Last Updated : 02 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

GDB, the acronym for GNU Debugger, is a powerful debugging tool used to analyze and debug programs written in languages like C, C++, Ada, and Fortran. It allows developers to inspect the behavior of their programs, step through code, set breakpoints, and examine variable values in real-time. GDB is an essential tool for debugging complex code, providing insights into runtime behavior that are invaluable for troubleshooting and optimization.

Basic Syntax of GDB

gdb [-help] [-nx] [-q] [-batch] [-cd=dir] [-f] [-b bps] [-tty=dev] [-s symfile] [-e prog] [-se prog] [-c core] [-x cmds] [-d dir] [prog[core|procID]]

Example:

The program to be debugged should be compiled with '-g' option. The below given C++ file that is saved as 'gfg.cpp'. We are going to use this file in this article.

CPP14
#include <iostream> #include <stdlib.h> #include <string.h> using namespace std;  int findSquare(int a) {     return a * a; }  int main(int n, char** args) {     for (int i = 1; i < n; i++)      {         int a = atoi(args[i]);         cout << findSquare(a) << endl;     }     return 0; } 

Preparing a Program for Debugging with GDB

Compile the above C++ program using the command:

g++ -g -o gfg gfg.cpp

To start the debugger of the above 'gfg' executable file, enter the command 'gdb gfg'. It opens the gdb console of the current program, after printing the version information.

Key Commands in GDB

1. run [args]

This command runs the current executable file. In the below image, the program was executed twice, one with the command line argument 10 and another with the command line argument 1, and their corresponding outputs were printed.

2. Quit GDB (quit or q):

To quit the gdb console, either quit or q can be used.

3. Get Help ('help')

It launches the manual of gdb along with all list of classes of individual commands.

4. Setting Breakpoints (break)

The command break [function name] helps to pause the program during execution when it starts to execute the function. It helps to debug the program at that point. Multiple breakpoints can be inserted by executing the command wherever necessary. 'b findSquare' command makes the gfg executable pause when the debugger starts to execute the findSquare function.

b
break [function name]
break [file name]:[line number]
break [line number]
break *[address]
break ***any of the above arguments*** if [condition]
b ***any of the above arguments***
In the above example, the program that was being executed(run 10 100), paused when it encountered findSquare function call. The program pauses whenever the function is called. Once the command is successful, it prints the breakpoint number, information of the program counter, file name, and the line number. As it encounters any breakpoint during execution, it prints the breakpoint number, function name with the values of the arguments, file name, and line number. The breakpoint can be set either with the address of the instruction(in hexadecimal form preceded with *0x) or the line number and it can be combined with if condition(if the condition fails, the breakpoint will not be set) For example, break findSquare if a == 10.

5. Continue Execution ('continue' or 'c')

This command helps to resume the current executable after it is paused by the breakpoint. It executes the program until it encounters any breakpoint or runs time error or the end of the program. If there is an integer in the argument(repeat count), it will consider it as the continue repeat count and will execute continue command "repeat count" number of times.

continue [repeat count]
c [repeat count]

6. Step Over ('next' or 'n')

This command helps to execute the next instruction after it encounters the breakpoint. Whenever it encounters the above command, it executes the next instruction of the executable by printing the line in execution.

7. Delete Breakpoints ('delete')

This command helps to deletes the breakpoints and checkpoints. If the delete command is executed without any arguments, it deletes all the breakpoints without modifying any of the checkpoints. Similarly, if the checkpoint of the parent process is deleted, all the child checkpoints are automatically deleted.

d
delete
delete [breakpoint number 1] [breakpoint number 2] ...
delete checkpoint [checkpoint number 1] [checkpoint number 2] ...
In the above example, two breakpoints were defined, one at the main and the other at the findSquare. Using the above command findSquare breakpoint was deleted. If there is no argument after the command, the command deletes all the breakpoints.

8. Clear Breakpoints ('clear')

This command deletes the breakpoint which is at a particular function with the name 'FUNCTION_NAME'. If the argument is a number, then it deletes the breakpoint that lies in that particular line.

clear [line number] 
clear [FUNCTION_NAME]
In the above example, once the clear command is executed, the breakpoint is deleted after printing the breakpoint number.

9. disable [breakpoint number 1] [breakpoint number 2] .... (disable and enable)

Instead of deleting or clearing the breakpoints, they can be disabled and can be enabled whenever they are necessary.

10. enable [breakpoint number 1] [breakpoint number 2] ....

To enable the disabled breakpoints, this command is used.

11. Inspect Breakpoints ('info breakpoints')

When the info breakpoints in invoked, the breakpoint number, type, display, status, address, the location will be displayed. If the breakpoint number is specified, only the information about that particular breakpoint will be displayed. Similarly, when the info checkpoints are invoked, the checkpoint number, the process id, program counter, file name, and line number are displayed.

info breakpoints [breakpoint number 1] [breakpoint number 2] ... 
info checkpoints [checkpoint number 1] [checkpoint number 2] ...

12. Checkpoints and Process Management (checkpoint and restart)

These command creates a new process and keep that process in the suspended mode and prints the created process's process id. For example, in the above execution, the breakpoint is kept at function findSquare and the program was executed with the arguments "1 10 100". When the function is called initially with a = 1, the breakpoint happens. Now we create a checkpoint and hence gdb returns a process id(4272), keeps it in the suspended mode and resumes the original thread once the continue command is invoked. Now the breakpoint happens with a = 10 and another checkpoint(pid = 4278) is created. From the info checkpoint information, the asterisk mentions the process that will run if the gdb encounters a continue. To resume a specific process, restart command is used with the argument that specifies the serial number of the process. If all the process are finished executing, the info checkpoint command returns nothing.

13. Set and Show Arguments (set args [arg1] [arg2] ...)

This command creates the argument list and it passes the specified arguments as the command line arguments whenever the run command without any argument is invoked. If the run command is executed with arguments after set args, the arguments are updated. Whenever the run command is ran without the arguments, the arguments are set by default.

14. show args

The show args prints the default arguments that will passed if the run command is executed. If either set args or run command is executed with the arguments, the default arguments will get updated, and can be viewed using the above show args command.

15. display [/format specifier] [expression] and undisplay [display id1] [display id2] ...

These command enables automatic displaying of expressions each time whenever the execution encounters a breakpoint or the n command. The undisplay command is used to remove display expressions. Valid format specifiers are as follows:

o - octal
x - hexadecimal
d - decimal
u - unsigned decimal
t - binary
f - floating point
a - address
c - char
s - string
i - instruction
In the above example, the breakpoint is set at line 12 and ran with the arguments 1 10 100. Once the breakpoint is encountered, display command is executed to print the value of i in hexadecimal form and value of args[i] in the string form. After then, whenever the command n or a breakpoint is encountered, the values are displayed again until they are disabled using undisplay command.

16. Print Expressions ('print')

This command prints the value of a given expression. The display command prints all the previously displayed values whenever it encounters a breakpoint or the next command, whereas the print command saves all the previously displayed values and prints whenever it is called.

print [Expression]
print $[Previous value number]
print {[Type]}[Address]
print [First element]@[Element count]
print /[Format] [Expression]

17. Load Executables ('file')

gdb console can be opened using the command gdb command. To debug the executables from the console, file [executable filename] command is used.

Conclusion

GDB is an indispensable tool for developers working with compiled languages like C and C++. Its robust set of debugging features makes it possible to pinpoint and resolve bugs, analyze program behavior, and optimize performance. By understanding and mastering GDB commands and options, you can greatly enhance your debugging skills, leading to more efficient and effective development.


L

Lokesh Karthikeyan
Improve
Article Tags :
  • Linux-Unix
  • Technical Scripter 2018

Similar Reads

    file command in Linux with examples
    The 'file' command in Linux is a vital utility for determining the type of a file. It identifies file types by examining their content rather than their file extensions, making it an indispensable tool for users who work with various file formats. The file type can be displayed in a human-readable f
    3 min read
    How to Find a File in Linux | Find Command
    The find command in Linux is used to search for files and directories based on name, type, size, date, or other conditions. It scans the specified directory and its sub directories to locate files matching the given criteria.find command uses are:Search based on modification time (e.g., files edited
    9 min read
    Finger command in Linux with Examples
    The 'finger' command is a powerful utility in Linux used to display information about users logged into the system. This command is commonly used by system administrators to retrieve detailed user information, including login name, full name, idle time, login time, and sometimes the user's email add
    4 min read
    fmt command in Linux with examples
    fmt command in LINUX actually works as a formatter for simplifying and optimizing text files. Formatting of text files can also be done manually, but it can be really time-consuming when it comes to large text files, this is where fmt comes to rescue. fmt re-formats each paragraph in the file specif
    4 min read
    fold command in Linux with examples
    The fold command in Linux wraps each line in an input file to fit a specified width and prints it to the standard output. By default, it wraps lines at a maximum width of 80 columns, which is configurable. To fold input using the fold command pass a file or standard input to the command. Syntax of `
    3 min read
    for command in Linux with Examples
    IntroductionThe for command in linux used in shell scripting to iterate over a set of values or perform set of tasks repeatedly. The for loop allows users to automate operations efficiently which is easier to maintain.Syntax: for NAME [in WORDS ... ] ; do COMMANDS; doneHere NAME takes the value of e
    2 min read
    free Command in Linux with examples
    While using LINUX there might come a situation when you are willing to install a new application (big in size) and you wish to know the amount of free memory available on your system. In LINUX, there exists a command line utility for this and that is the 'free' command which displays the total amoun
    6 min read
    Fun Commands in Linux
    Linux isn't just for coding and administration—it can also be a lot of fun. With a variety of terminal commands, you can add some entertainment to your Linux experience. Below is a list of some cool and fun commands you can use in Linux to enhance your terminal experience. We’ll also cover how to in
    3 min read
    function command in Linux with examples
    The function is a command in Linux that is used to create functions or methods. It is used to perform a specific task or a set of instructions. It allows users to create shortcuts for lengthy tasks making the command-line experience more efficient and convenient. The function can be created in the u
    2 min read
    Compiling with g++
    g++ command is a GNU c++ compiler invocation command, which is used for preprocessing, compilation, assembly and linking of source code to generate an executable file. The different "options" of g++ command allow us to stop this process at the intermediate stage.   Check g++ compiler version informa
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences