如何优雅在vscode上调试c++程序呢?首先需要安装相关的工具:
sudo apt update
sudo apt install build-essential gdb
然后安装对应的扩展:
打开 VS Code,安装扩展:
C/C++(Microsoft 出品)
C/C++ Extension Pack(可选,包含调试支持)
code runner等等
安装好扩展之后建立一个专门用于cpp的文件夹,然后创建配置文件到.vscode中:
写入配置(不用修改)tasks.json:
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ 生成活动文件",
"command": "/usr/bin/g++",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "调试器生成的任务。"
}
],
"version": "2.0.0"
}
launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug C++",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}",
"args": [],
"stopAtEntry": false,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "build cpp",
"miDebuggerPath": "/usr/bin/gdb"
}
]
}
其他的就默认就行了。
创建一个简单的c++程序:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, Ubuntu + VS Code!" << endl;
return 0;
}
打上断点,尽情调试即可:
如果是调试和运行单个/多个程序呢?
第一种方式是通过指定所有的cpp到args中:
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"label": "build multi-cpp",
"command": "/usr/bin/g++",
"args": [
"-g",
"src/main.cpp",
"src/foo.cpp",
"src/bar.cpp",
"-I", "include",
"-o", "${workspaceFolder}/bin/app"
],
"group": { "kind": "build", "isDefault": true },
"problemMatcher": ["$gcc"]
}
]
}
同步修改launch.json,把program指定到上一步生成的可执行文件:
"program": "${workspaceFolder}/bin/app",
"preLaunchTask": "build multi-cpp",
对应的结构:
cpp_proj
├── .vscode
│ ├── tasks.json
│ └── launch.json
├── include
│ └── bar.h
├── src
│ ├── main.cpp
│ ├── foo.cpp
│ └── bar.cpp
└── bin
└── app (生成的可执行文件)
第二种则是通过cmake/makefile来进行简化.这里就不再赘述了.
另外就是程序格式的整理了,使用clang-format工具,首先安装相应的工具:
sudo apt install clang-format
然后生成.clang-format文件:
clang-format -style=llvm -dump-config > .clang-format
然后安装插件:
配置插件中的位置:
使用时,对于需要整理的代码,右键进行格式化文档
缩进信息就没有问题了.