linux下调试C++程序一般用gdb或log的方式,gdb虽然能断点单步调试,但是纯命令行调试不够方便直观,vscode推出了远程调试的一些插件,可以方便的搭建linux下的C++开发、调试环境,下面就一步步打造linux的的开发环境吧
安装插件 Remote - SSH
,Remote - WSL
,Remote Development
, C/C++
,全部选微软官方的版本
添加要连接的远程机器,wsl和ssh的操作方式是一样的,只是ssh需要配置一下ssh登录,这个随便一搜就有了
在远程机器上安装vscode插件(此时我们的环境已经在远程机器上了)
sudo apt install g++ make gdb
gdb/lldb
那一栏.vscode目录
下会出现两个文件,顾名思义,launch.json是启动调试的入口文件,task是其他子任务这个文件定义了一些任务,可以再launch.json中调用
默认长这样:
需要注意的是,不能在一个字符串中写多个命令选项,会报错,需要拆开
,比如:
g++ "-Werror=format -std=c++17 -L. -lNanoLog -pthread -lrt"
完整launch.jons:
{
// 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++-9 - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/sampleApplication",
"args": [],
"stopAtEntry": false,
"cwd": "${fileDirname}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: g++-9 build active file",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
完整task.json
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++-9 build active file",
"command": "/usr/bin/g++-9",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/sampleApplication",
"-I", "../runtime",
"-Werror=format", "-std=c++17",
"-L.", "-lNanoLog", "-pthread", "-lrt"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
打好断点,按下F5,就能像visualstudo中一样方便的调试了
上面我们使用的是g++进行编译的,但是很多开源项目都是用的make进行构建的,那我们来调整一下task.json,然他支持make;
其实经过上面的配置,我们能理解到,task.json其实就是配置一下构建的命令而已,所以我们把command修改为make
,args修改为make对于的命令参数
即可,
使用make要注意makefile的位置和工作路径的位置关系,不然容易出现找不到makefile的问题
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++-9 build active file",
"command": "make",
"args": [
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
],
"version": "2.0.0"
}
launch.json、task.json中的一些预定义变量查询:
https://code.visualstudio.com/docs/editor/variables-reference