用 VS Code 调试C/C++工程步骤总结(简洁版)
一、编写CMakeLists.txt 文件
简单模板如下:
cmake_minimum_required(VERSION 3.0)
project(SOLIDERFIRE)
#在g++编译时,添加编译参数,比如-Wall可以输出一些警告信息
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
#一定要加上这句话,加上这个生成的可执行文件才是可以Debug的,不然不加或者是Release的话生成的可执行文件是无法进行调试的
set(CMAKE_BUILD_TYPE Debug)
#添加头文件
include_directories(include)
#或者通过绝对路径来进行添加,include_directories(${CMAKE_SOURCE_DIR}/include)
#其中${CMAKE_SOURCE_DIR}就是VSCODE_C_LEARNING_3这个文件夹的绝对路径
add_executable(my_cmake_exe main.cpp src/Gun.cpp src/Solider.cpp)
按照要求对 add_executable 中文件进行更改
若别人的工程中已经有 CMakeLists.txt 文件,则这一步直接省略
二、添加 launch.json 文件
然后选择第一个 C++(GDB/LLDB),然后选择第一个 g++:生成和调试活动文件,
可以得到如下 launch.json 模板,替换为下面模板:
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "g++ - 生成和调试活动文件",
"type": "cppdbg",
"request":"launch",
"program":"${workspaceFolder}/build/my_cmake_exe",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "为 gdb 启动整齐打印",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "Build",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
正常需要更改里面两个参数:“program” 和 “preLaunchTask”,这里对 “preLaunchTask” 不进行更改,只改"program",将里面的build后面的可执行文件名字改为 CMakeLists.txt 中 add_executable中可执行文件的名字。
三、添加tasks.json 文件
点击 选项栏 Terminal->Configure Default Build Task,然后随便选择一个,建立一个 task.json 文件。
将tasks.json替换为下面模板
{
"version": "2.0.0",
"options":{
"cwd": "${workspaceFolder}/build" //指明在哪个文件夹下做下面这些指令
},
"tasks": [
{
"type": "shell",
"label": "cmake", //label就是这个task的名字,这个task的名字叫cmake
"command": "cmake", //command就是要执行什么命令,这个task要执行的任务是cmake
"args":[
".."
]
},
{
"label": "make", //这个task的名字叫make
"group": {
"kind": "build",
"isDefault": true
},
"command": "make", //这个task要执行的任务是make
"args": [
]
},
{
"label": "Build",
"dependsOrder": "sequence", //按列出的顺序执行任务依赖项
"dependsOn":[ //这个label依赖于上面两个label
"cmake",
"make"
]
}
]
}
不用更改。
四、保存调试即可
系统会自动进行编译和调试。(通过launch.json中的 "preLaunchTask"完成的,而这个就是 tasks.json 完成的)
对程序更改后直接调试即可。不用手动编译。