ubuntu

C++程序在Ubuntu上如何调试

小樊
48
2025-04-02 09:06:22
栏目: 编程语言

在Ubuntu上调试C++程序,你可以使用多种工具和方法。以下是使用Visual Studio Code(VS Code)进行调试的详细步骤:

准备工作

  1. 安装编译器和调试器
sudo apt update
sudo apt install build-essential
sudo apt install gdb
  1. 安装Visual Studio Code
  1. 安装C/C++扩展

配置VS Code进行调试

  1. 创建一个新的C++项目
  1. 配置tasks.json文件
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "command": "g++",
            "args": [
                "-g",
                "-O0",
                "${file}",
                "-std=c++11",
                "-D_GLIBCXX_DEBUG",
                "-o",
                "${fileBasenameNoExtension}"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}
  1. 配置launch.json文件
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "(gdb) Launch",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/${fileBasenameNoExtension}",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "preLaunchTask": "build",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ]
        }
    ]
}
  1. 编译和调试代码
g++ -g main.cpp -o main

使用GDB进行调试

如果你更喜欢使用命令行工具GDB,可以按照以下步骤进行调试:

  1. 编译程序时包含调试信息
g++ -g your_file.cpp -o your_executable
  1. 启动GDB
gdb your_executable
  1. 设置断点
break function_name
  1. 运行程序
run
  1. 调试命令

通过以上步骤,你可以在Ubuntu上使用VS Code或GDB调试C++程序。选择适合你的方法,并根据需要进行调整和扩展。

0
看了该问题的人还看了