vscode使用配置指南

  • ~15.49K 字
  1. 1. vscode 使用配置指南
  2. 2. vscode 配置的关键字指南
  3. 3. c/cpp 优化
    1. 3.1. include优化
    2. 3.2. 代码跳转、补全等的来源项
    3. 3.3. clang 在vscode的使用(非编译)
    4. 3.4. 关于tidy的启用
    5. 3.5. cpp-tools 的 vcformat
  4. 4. cpp 调试以及调试配置
    1. 4.1. 调试控制台使用方法
    2. 4.2. lldb 调试
  5. 5. 针对不同文件的编码优化
  6. 6. 针对工作区、文件夹的特殊设置
  7. 7.

vscode 使用配置指南

vscode设置主要围绕.vscode/目录展开,包括特定语言配置文件和settings.json,文件,以及调试用launch.json文件和tasks.json文件,额外的会在文件夹根目录创建.xxxx等配置文件进行进一步扩展

配置包括:

官网资源:

vscode 配置的关键字指南

vscode配置里的关键字,官网连接:Variables reference

建议看官网解释,有输入和命令关键字,高级用法。

变量 作用 中文
${userHome} Path of the user’s home folder 用户home目录
${workspaceFolder} Path of the folder opened in VS Code 打开的文件夹路径
${workspaceFolderBasename} Name of the folder opened in VS Code without any slashes (/) 打开的文件夹名
${file} Currently opened file 当前打开的文件
${fileWorkspaceFolder} Currently opened file’s workspace folder 挡开打开的文件的工作区文件夹名
${relativeFile} Currently opened file relative to workspaceFolder
${relativeFileDirname} Currently opened file’s dirname relative to workspaceFolder
${fileBasename} Currently opened file’s basename
${fileBasenameNoExtension} Currently opened file’s basename with no file extension
${fileExtname} Currently opened file’s extension
${fileDirname} Currently opened file’s folder path
${fileDirnameBasename} Currently opened file’s folder name
${cwd} Task runner’s current working directory upon the startup of VS Code
${lineNumber} Currently selected line number in the active file
${columnNumber} Currently selected column number in the active file
${selectedText} Currently selected text in the active file
${execPath} Path to the running VS Code executable
${defaultBuildTask} Name of the default build task
${pathSeparator} Character used by the operating system to separate components in file paths
${/} Shorthand for ${pathSeparator}

作用举例:
Suppose that you have the following conditions:

  • A file located at /home/your-username/your-project/folder/file.ext opened in your editor;
  • The directory /home/your-username/your-project opened as your root workspace.
    This leads to the following values for each of the variables:
  • ${userHome}: /home/your-username
  • ${workspaceFolder}: /home/your-username/your-project
  • ${workspaceFolderBasename}: your-project
  • ${file}: /home/your-username/your-project/folder/file.ext
  • ${fileWorkspaceFolder}: /home/your-username/your-project
  • ${relativeFile}: folder/file.ext
  • ${relativeFileDirname}: folder
  • ${fileBasename}: file.ext
  • ${fileBasenameNoExtension}: file
  • ${fileExtname}: .ext
  • ${fileDirname}: /home/your-username/your-project/folder
  • ${fileDirnameBasename}: folder
  • ${lineNumber}: line number of the cursor
  • ${columnNumber}: column number of the cursor
  • ${selectedText}: text selected in your code editor
  • ${execPath}: location of Code.exe
  • ${pathSeparator}: / on macOS or linux, \ on Windows

c/cpp 优化

c cpp语言优化与支持,需要依赖以下文件:

  • .vscode\c_cpp_properties.json: c cpp 的intellisence 配置文件,为c语言函数跳转,提示等提供基础的环境和目录以及宏定义等
  • .vscode\settings.json: 更改配置使用
  • .vscode/launch.json: 开启调试
  • .vscode/tasks.json: 执行任务,编译,清理等
  • 额外的可能还需要以下文件
  • .clangd: clangd 的动态语法检查,函数提示跳转等强力功能的配置文件,该功能与上述intellisence冲突
  • .clang-format: clang 强大的format配置文件
  • .clang-tidy: clang 静态语法检查

include优化

文件:.vscode\c_cpp_properties.json, 针对无项目管理的项目,比如makafile项目(eclipse), cmake项目建议使用下述的cmake配置提供器;示例内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
"configurations": [
{
"name": "h503_ext_demo",
"cStandard": "c11",
"cppStandard": "c++11",
"compilerArgs": [
"--target=arm-arm-none-eabi"
],
"intelliSenseMode": "clang-arm",
"includePath": [
"D:/Program Files (x86)/Keil_v5/ARM/ARMCLANG/include",
"Core/Inc",
"USBX/App",
"USBX/Target",
"Drivers/STM32H5xx_HAL_Driver/Inc",
"Drivers/STM32H5xx_HAL_Driver/Inc/Legacy",
"Drivers/CMSIS/Device/ST/STM32H5xx/Include",
"Middlewares/ST/usbx/common/core/inc",
"Middlewares/ST/usbx/ports/generic/inc",
"Middlewares/ST/usbx/common/usbx_stm32_device_controllers",
],
"defines": [
"UX_INCLUDE_USER_DEFINE_FILE",
"USE_HAL_DRIVER",
"STM32H503xx",
],
"intelliSenseMode": "gcc-arm",
"compilerPath": "arm-none-eabi-gcc.exe",
}
],
"version": 4
}

代码跳转、补全等的来源项

文件:.vscode\settings.json,建议设置为cmake项目,非cmake项目需要配置include path才行。内容:

1
2
3
{
"C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools",
}

clang 在vscode的使用(非编译)

参考链接:

作用:

  1. clang-format 实现更加全面的代码格式化
  2. clangd 提供代码检查、跳转、补全等功能
  3. clang-tidy 提供静态检查

C/Cpp扩展自带clang-format执行程序,和dity, 关于clangd clang-format clang-tidy,针对cmake项目,cmake-tools提供include,intelliSence提供跳转和补全,c/cpp提供format和静态分析;

若安装了clangd一整套且拥有llvm环境,那么推荐使用clangd扩展接管intelliSence 和 c/cpp 功能,clangd 插件与c/cpp插件冲突,只能二选一;cmake-tools只提供include优化。

方案1:只使用c/cpp,和cmake-tools,文件.vscode\settings.json,内容:

1
2
3
4
{
"C_Cpp.formatting": "clangFormat", // 默认是file,必须需要项目目录内自带 .clang-format 文件,否则就手动在设置里调配format格式
"editor.formatOnSave": false // 可选
}

方案2:只使用clangd,和cmake-tools,文件.vscode\settings.json,内容:这里只启用了clangd的代码检查未启用格式化,已启用tidy,严格依赖cmake,不然没有compile_commands.json。keil项目有插件可以实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
{
"C_Cpp.intelliSenseEngine": "disabled",
"clangd.arguments": [
"--all-scopes-completion", // 全局补全(补全建议会给出在当前作用域不可见的索引,插入后自动补充作用域标识符),例如在main()中直接写cout,即使没有`#include <iostream>`,也会给出`std::cout`的建议,配合"--header-insertion=iwyu",还可自动插入缺失的头文件
"--background-index", // 后台分析并保存索引文件
"--clang-tidy", // 启用 Clang-Tidy 以提供「静态检查」,下面设置 clang tidy 规则
"--clang-tidy-checks=performance-*, bugprone-*, misc-*, google-*, modernize-*, readability-*, portability-*",
"--compile-commands-dir=${workspaceFolder}/build/Debug", // 编译数据库(例如 compile_commands.json 文件)的目录位置
"--completion-parse=auto", // 当 clangd 准备就绪时,用它来分析建议
"--completion-style=detailed", // 建议风格:打包(重载函数只会给出一个建议);还可以设置为 detailed
// "--query-driver=arm-none-eabi-gcc", // MacOS 上需要设定 clang 编译器的路径,homebrew 安装的clang 是 /usr/local/opt/llvm/bin/clang++
"--query-driver=D:\\DevTools\\arm-gnu-toolchain-13.3.rel1-mingw-w64-i686-arm-none-eabi\\bin\\arm-none-eabi-gcc.exe", // MacOS 上需要设定 clang 编译器的路径,homebrew 安装的clang 是 /usr/local/opt/llvm/bin/clang++
// 启用配置文件(YAML格式)项目配置文件是在项目文件夹里的“.clangd”,用户配置文件是“clangd/config.yaml”,该文件来自:Windows: %USERPROFILE%\AppData\Local || MacOS: ~/Library/Preferences/ || Others: $XDG_CONFIG_HOME, usually ~/.config
"--enable-config",
"--fallback-style=Microsoft", // 默认格式化风格: 在没找到 .clang-format 文件时采用,可用的有 LLVM, Google, Chromium, Mozilla, Webkit, Microsoft, GNU
"--function-arg-placeholders=false", // 补全函数时,将会给参数提供占位符,键入后按 Tab 可以切换到下一占位符,乃至函数末
"--header-insertion-decorators", // 输入建议中,已包含头文件的项与还未包含头文件的项会以圆点加以区分
"--header-insertion=iwyu", // 插入建议时自动引入头文件 iwyu
"--include-cleaner-stdlib", // 为标准库头文件启用清理功能(不成熟!!!)
"--log=verbose", // 让 Clangd 生成更详细的日志
"--pch-storage=memory", // pch 优化的位置(Memory 或 Disk,前者会增加内存开销,但会提升性能)
"--pretty", // 输出的 JSON 文件更美观
"--ranking-model=decision_forest", // 建议的排序方案:hueristics (启发式), decision_forest (决策树)
"-j=4" // 同时开启的任务数量
],
"editor.formatOnSave": true,
"[cpp]": {
"editor.defaultFormatter": "llvm-vs-code-extensions.vscode-clangd"
},
"editor.formatOnSave": false //可选
}

总结:电脑够强直接clangd全套。

上述案例中用到的.clang-format文档:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
Language: Cpp
# ==================== 基础缩进与风格 ====================
# 基于 LLVM 风格进行修改,这是一个严谨的起点
BasedOnStyle: LLVM
# 使用空格,而非 Tab 字符
UseTab: Never
# 一个缩进级别 = 4个空格
TabWidth: 4
IndentWidth: 4

# ==================== 大括号换行规则 ====================
# 这是实现你“语句后挂{,函数{换行”要求的关键配置
BraceWrapping:
# 函数定义的大括号换行(对应你的要求)
AfterFunction: true
# 控制语句(if/while/for等)的大括号不换行
# AfterControlStatement: Multiline
AfterEnum: false
AfterStruct: false
AfterClass: false
AfterUnion: false
BeforeElse: false
BeforeCatch: false
BeforeWhile: false
# 旧版全局大括号换行控制,设置为Linux风格(函数换行,控制语句不换行)
BreakBeforeBraces: Linux

# ==================== 指针与引用 ====================
# 指针和引用的`*`、`&`符号紧贴类型,而不是变量名
PointerAlignment: Left
DerivePointerAlignment: false

# ==================== 空格控制 ====================
# 在圆括号内部插入空格
SpacesInParentheses: false
# 在方括号内部插入空格
SpacesInSquareBrackets: false
# 在关键字(如if, for, while)与后面的左括号之间加空格
SpaceBeforeParens: ControlStatements
# 在赋值运算符(=, +=等)和其他二元运算符(+, -, *, /, %)前后加空格
SpaceBeforeAssignmentOperators: true
# 确保逗号后有空格,前面无空格
SpacesInCStyleCastParentheses: false
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceInEmptyParentheses: false
# 确保函数声明/定义时,函数名与参数列表开头的‘(’之间无空格
# SpaceBeforeParens: ControlStatements
# 控制语句(if/for/while)关键字与后面的‘(’之间有一个空格
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterFunctionDeclarationName: false
# 确保二元运算符(如 +, -, *, /, =, ==)左右有空格
SpacesInConditionalStatement: false
AllowShortFunctionsOnASingleLine: None
# 确保一元运算符(如 ++, --, !, ~)与操作数之间无空格
SpacesInContainerLiterals: false

# ==================== 行与列限制 ====================
# 行宽限制为80列
ColumnLimit: 120
# 允许函数调用参数过长时自动分行
AllowAllParametersOfDeclarationOnNextLine: false
BinPackParameters: false
# 函数声明的参数如果过长,自动分行
AllowAllArgumentsOnNextLine: false
BinPackArguments: false

# ==================== 注释格式 ====================
# 重新排版注释,使其符合ColumnLimit限制
ReflowComments: true
# 单行注释(//)前至少保留2个空格(若从行首开始则不需要)
SpacesBeforeTrailingComments: 2
# 多行注释格式:保持`/**`开始,每行`*`对齐,`*/`结束的风格
# ClangFormat会尽力保持你手动编写的多行注释格式

以下是更加完全完整的.clang-format文档

关于tidy的启用

  1. clangd,项目打开后会非常占用cpu
  2. cpptools,项目打开后会非常占用cpu,推荐设置里调试
  3. cmake,推荐cmake结合tidy,编译时检查,编译时非常占用cpu

目前搁置;嵌入式项目暂时不建议启用。

cpp-tools 的 vcformat

针对单独的格式格式化,推荐使用,自定义成都比较高,但是格式化项少。
文件.vscode\settings.json, “C_Cpp.vcformat.xxxxx”项,推荐文件设置,不用设置的ui。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
// settings.json
"C_Cpp.formatting": "vcFormat",
"C_Cpp.vcFormat.indent.preserveWithinParentheses": true,
"C_Cpp.vcFormat.space.afterComma": true,
"C_Cpp.vcFormat.space.betweenEmptyBraces": true,
"C_Cpp.vcFormat.space.beforeInitializerListOpenBrace": false,
"C_Cpp.vcFormat.space.withinSquareBrackets": false,
"C_Cpp.vcFormat.space.withinInitializerListBraces": false,
"C_Cpp.vcFormat.space.withinControlFlowStatementParentheses": false,
"C_Cpp.vcFormat.space.betweenEmptyLambdaBrackets": true,
"C_Cpp.vcFormat.space.afterCastCloseParenthesis": true,
"C_Cpp.vcFormat.newLine.beforeOpenBrace.block": "sameLine",
"C_Cpp.vcFormat.newLine.closeBraceSameLine.emptyType": true,
"C_Cpp.vcFormat.newLine.beforeElse": false,
"C_Cpp.autocompleteAddParentheses": true,
}

cpp 调试以及调试配置

主要依靠.vscode/launch.json.vscode/tasks.json文件,一个是启动调试,一个是创建用户任务。

简单项目可以依靠c语言的插件,cpp多文件插件:C/C++ Runner(franneck94);单文件C/C++ Compile Run danielpinto8zz6

有编译过程(makefile)的可以使用tasks和launch

cmake的用cmake

文件.vscode/launch.json,创建调试配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{
"version": "0.2.0",
"configurations": [
{
"name": "调试名字",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/xxx", // 当前文件的输出路径
"args": [],
"stopAtEntry": true,
"cwd": "${workspaceFolder}",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "为 gdb 启用整齐打印",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
],
"preLaunchTask": "C/C++: g++ 生成活动文件"
}
]
}

文件.vscode/tasks.json配置内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
{
"tasks": [
{
"type": "shell",
"label": "C/C++: g++ 生成活动文件", // 编译任务的名称,跟上面preLaunchTask的值对应
"command": "/usr/bin/g++", // g++路径
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$gcc"
],
"group": {
"kind": "build",
"isDefault": true
}
}
],
"version": "2.0.0"
}

调试控制台使用方法

开始调试后,调试控制台直连调试器,使用exec 开头的指令,后跟调试器指令即可,比如exec print a,支持命令简称exec p a

gdb调试命令 可看GDB调试命令详解

命令 作用
(gdb) break (b) 在源代码指定的某一行设置断点,其中xxx用于指定具体打断点位置
(gdb) run (r) 执行被调试的程序,其会自动在第一个断点处暂停执行。
(gdb) continue (c) 当程序在某一断点处停止后,用该指令可以继续执行,直至遇到断点或者程序结束。
(gdb) next (n) 令程序一行代码一行代码的执行。
(gdb) step(s) 如果有调用函数,进入调用的函数内部;否则,和 next 命令的功能一样。
(gdb) until (u) (gdb) until (u) location 当你厌倦了在一个循环体内单步跟踪时,单纯使用 until 命令,可以运行程序直到退出循环体。 until n 命令中,n 为某一行代码的行号,该命令会使程序运行至第 n 行代码处停止。
(gdb) print (p) 打印指定变量的值,其中 xxx 指的就是某一变量名。
(gdb) list (l) 显示源程序代码的内容,包括各行代码所在的行号。
(gdb) finish(fi) 结束当前正在执行的函数,并在跳出函数后暂停程序的执行。
(gdb) return(return) 结束当前调用函数并返回指定值,到上一层函数调用处停止程序执行。
(gdb) jump(j) 使程序从当前要执行的代码处,直接跳转到指定位置处继续执行后续的代码。
(gdb) quit (q) 终止调试。

打印数组:

1
2
3
4
5
#print byte array
p/x *(uint8_t(*)[10])ptr

#print long string:
set set target.max-string-summary-length 10000

lldb 调试

挖坑

针对不同文件的编码优化

文件:.vscode\settings.json,内容:

1
2
3
4
5
6
7
8
9
10
11
{
// 针对语言文件
"[c]": {
"editor.wordBasedSuggestions": "off",
"editor.semanticHighlighting.enabled": true,
"editor.stickyScroll.defaultModel": "foldingProviderModel",
"editor.suggest.insertMode": "replace",
"files.encoding": "gbk"
}
}

针对工作区、文件夹的特殊设置

打赏
打赏提示信息
分享
分享提示信息