Complete Guide to Passing Command Line Arguments in GDB on Linux

Nov 30, 2025 · Programming · 14 views · 7.8

Keywords: GDB Debugging | Command Line Arguments | Linux Development

Abstract: This article provides a comprehensive guide to passing command line arguments in the GNU Debugger (GDB) within Linux environments. Through in-depth analysis of GDB's core commands and working principles, it presents a complete workflow from basic compilation to advanced debugging. The focus is on the standardized approach using the run command, supplemented with practical code examples and step-by-step instructions to help developers master effective command line argument management in GDB debugging sessions.

Overview of GDB Debugger and Command Line Argument Passing

The GNU Debugger (GDB) is a powerful program debugging tool in Linux environments, widely used in the development and debugging of languages like C and C++. In practical debugging scenarios, programs often need to receive specific command line arguments to simulate real execution environments or trigger particular execution paths. Correctly passing command line arguments is crucial for reproducing and locating program errors.

Program Compilation and Debug Information Generation

Before starting debugging, it's essential to ensure the program is compiled with debugging information. For C programs using the GCC compiler, the -g option must be used to enable debug symbol generation:

gcc -g -o InsertionSortWithErrors InsertionSortWithErrors.c

This command compiles the source code into the executable InsertionSortWithErrors and embeds detailed debugging information, including variable names, function names, and source code line numbers. This metadata forms the foundation for GDB's symbolic debugging capabilities.

GDB Startup and Program Loading

The standard command format for starting GDB and loading the target program is:

gdb InsertionSortWithErrors

After executing this command, GDB enters an interactive debugging session, displaying the (gdb) prompt and waiting for user input. At this point, the program is loaded into memory but has not yet begun execution.

Using the run Command to Pass Command Line Arguments

Within the GDB session, the run command (abbreviated as r) is used to start program execution. This command supports direct attachment of command line arguments with the syntax:

run arg1 arg2 arg3

Where arg1, arg2, arg3 represent the actual arguments to be passed to the program. For example, if the program is normally executed as:

./InsertionSortWithErrors input.txt output.txt

The corresponding debugging command in GDB should be:

(gdb) run input.txt output.txt

GDB will pass these arguments completely to the program's main function, simulating the real command line execution environment.

Argument Handling and Special Character Escaping

When command line arguments contain spaces or other special characters, quotes must be used to ensure proper argument parsing:

run "file name with spaces.txt" "output file.txt"

This approach ensures that filenames containing spaces are passed as single arguments to the program, avoiding argument splitting errors.

Complete Workflow of a Debugging Session

A typical GDB debugging session includes the following key steps:

  1. Setting Breakpoints: Pause program execution at critical code locations
  2. break main
    break 42  # Set breakpoint at line 42
  3. Starting the Program: Launch the program with arguments using the run command
  4. run arg1 arg2
  5. Execution Control: Control program execution flow using stepping commands
  6. next    # Execute next line, skip function calls
    step    # Step into function calls
    continue # Continue until next breakpoint
  7. Variable Inspection: Monitor program state and variable values in real-time
  8. print variable_name
    info locals
    info registers
  9. Stack Tracing: Analyze function call relationships
  10. backtrace
    frame 1

Alternative Method: Using the --args Option

In addition to using the run command within the GDB session, program arguments can be pre-specified when starting GDB using the --args option:

gdb --args InsertionSortWithErrors arg1 arg2

This method sets the program arguments while starting GDB. After entering the debugging session, the program can be started directly using the run command without repeating the arguments. Note that support for this option may vary across different GDB versions.

Practical Debugging Example Analysis

Consider a sorting program that processes file input and output, with core argument handling logic as follows:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Usage: %s <input_file> <output_file>\n", argv[0]);
        return 1;
    }
    
    // File processing logic
    printf("Processing input: %s\n", argv[1]);
    printf("Output will be saved to: %s\n", argv[2]);
    
    return 0;
}

When debugging this program in GDB, the correct argument passing approach is:

gdb InsertionSortWithErrors
(gdb) break main
(gdb) run data.txt sorted_data.txt

The program will pause at the main function entry point, where you can verify correct argument passing using print argv[1] and print argv[2].

Argument Passing in TUI Mode

For developers preferring graphical interfaces, GDB provides Text User Interface (TUI) mode:

gdb -tui InsertionSortWithErrors

In TUI mode, argument passing works identically to standard mode. The interface is divided into source code display and command input areas. Developers can execute the run command with arguments in the command input area while observing program execution status in real-time in the source code area.

Debugging Techniques and Best Practices

Effective command line argument debugging requires following these best practices:

Common Issues and Solutions

During practical debugging, the following typical issues may arise:

Using GDB's variable monitoring and memory inspection features, these issues can be quickly located and resolved.

Conclusion and Extended Applications

Mastering command line argument passing in GDB is a fundamental skill for efficient debugging. Through the built-in argument support of the run command, developers can completely reproduce the program's real execution environment, which is particularly important for diagnosing errors related to specific inputs. Combined with core debugging functions like breakpoint setting, variable monitoring, and step execution, systematic debugging workflows can be constructed, significantly improving software quality and development efficiency.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.