在Ubuntu上使用C++進行代碼調試,通常會用到GDB(GNU調試器)或者集成開發環境(IDE)如CLion、Visual Studio Code等提供的調試功能。以下是使用GDB和Visual Studio Code進行調試的基本步驟:
編譯代碼:
在編譯C++代碼時,需要添加-g
選項來生成調試信息。
g++ -g -o myprogram myprogram.cpp
啟動GDB: 使用GDB啟動你的程序。
gdb myprogram
設置斷點:
在GDB中,你可以使用break
命令設置斷點。
break main
或者在特定函數中設置斷點:
break myFunction
運行程序:
使用run
命令啟動程序。
run
單步執行:
使用step
命令逐行執行代碼。
step
或者使用next
命令執行下一行代碼,但不進入函數內部。
next
查看變量:
使用print
命令查看變量的值。
print variableName
繼續執行:
使用continue
命令繼續執行程序直到下一個斷點。
continue
退出GDB:
使用quit
命令退出GDB。
quit
安裝C++擴展: 在Visual Studio Code中,安裝C++擴展(由Microsoft提供)。
配置launch.json:
在.vscode
文件夾中創建或編輯launch.json
文件,配置調試設置。例如:
{
"version": "0.2.0",
"configurations": [
{
"name": "g++ build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"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": "g++ build active file",
"internalConsoleOptions": "neverOpen"
}
]
}
編譯代碼:
在Visual Studio Code中,你可以使用任務(Task)來編譯代碼。在.vscode
文件夾中創建或編輯tasks.json
文件,配置編譯任務。例如:
{
"version": "2.0.0",
"tasks": [
{
"label": "g++ build active file",
"type": "shell",
"command": "g++",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": [
"$gcc"
]
}
]
}
啟動調試: 點擊Visual Studio Code左側的調試圖標,選擇配置好的調試環境,然后點擊綠色的“開始調試”按鈕。
調試操作: 調試過程中,你可以使用調試工具欄中的按鈕進行單步執行、繼續、停止等操作,也可以在“變量”、“監視”、“調用堆?!钡却翱谥胁榭聪嚓P信息。
以上就是在Ubuntu上使用C++進行代碼調試的基本步驟。根據你的具體需求和偏好,可以選擇使用GDB命令行工具或者集成開發環境的調試功能。