ubuntu

ubuntu如何调试gcc编译程序

小樊
47
2025-06-04 22:34:46
栏目: 智能运维

在Ubuntu系统中调试使用GCC编译的程序,可以采用以下几种方法:

1. 使用GDB进行调试

安装GDB

sudo apt update
sudo apt install gdb

编译程序时添加调试信息

gcc -g -o myprogram myprogram.c

-g选项会在生成的可执行文件中包含调试信息。

启动GDB

gdb myprogram

在GDB中进行调试

2. 使用LLDB进行调试

安装LLDB

sudo apt update
sudo apt install lldb

编译程序时添加调试信息

gcc -g -o myprogram myprogram.c

启动LLDB

lldb myprogram

在LLDB中进行调试

3. 使用Visual Studio Code进行调试

安装Visual Studio Code

sudo snap install --classic code

安装C/C++扩展 在VS Code中打开扩展市场,搜索并安装“C/C++”扩展。

配置launch.json 在VS Code的.vscode目录下创建或编辑launch.json文件,配置调试设置。例如:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "GCC Debug",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/myprogram",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "miDebuggerPath": "/usr/bin/gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "preLaunchTask": "gcc build active file"
        }
    ]
}

配置tasks.json.vscode目录下创建或编辑tasks.json文件,配置编译任务。例如:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "gcc build active file",
            "type": "shell",
            "command": "gcc",
            "args": [
                "-g",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "problemMatcher": [
                "$gcc"
            ]
        }
    ]
}

4. 使用AddressSanitizer进行内存错误检测

编译程序时启用AddressSanitizer

gcc -fsanitize=address -o myprogram myprogram.c

运行程序

./myprogram

AddressSanitizer会在运行时检测内存错误,如缓冲区溢出、使用未初始化的内存等,并输出详细的错误报告。

通过以上方法,你可以在Ubuntu系统中有效地调试使用GCC编译的程序。选择适合你需求的方法进行调试即可。

0
看了该问题的人还看了