VS Code 调教日记(2024.10.14 更新)
有关 VS Code 的各种配置
基于 msys2 配置 MinGW-w64 GCC
-
下载并安装 msys2 。
-
到路径
msys2安装路径\msys64\etc\pacman.d
下找到mirrorlist
文件,并将国内大学镜像源(如清华、中科大等)提至最前。这里只用到
.mingw32
、.mingw64
、.msys
三个镜像列表,有别的环境需要可以自己改。改完有可能之后会出现
.pacnew
文件,这是msys2
做的备份不用管。 -
执行
pacman -Syu
更新 pacman 的基本软件仓库。 -
执行
pacman -Su
更新的剩余程序。 -
执行
pacman -S --needed base-devel mingw-w64-x86_64-toolchain
安装 Mingw-w64 GCC 编译工具链。 -
系统全局环境变量
PATH
里添加路径msys2安装路径\msys64\mingw64\bin
。如果有别的mingw的路径请删除。
-
打开cmd,输入
g++ --version
,如果出现版本号则说明环境搭建完毕。
配置 vscode 的 C/C++ 编程环境
- 下载并安装 vscode 。
- 下载并配置 C/C++ 插件,配置后在项目内的
.vscode
下会出现c_cpp_properties.json
文件。 - 写个代码按 F5 ,进入配置编译器
tasks.json
和launch.json
,下面会给出具体配置。 - 再按 F5 开始调试。
- 开始玩别的插件qwq。
c_cpp_properties.json
C/C++ 插件配置,一般通过 Ctrl+Shift+P ,搜索插件名字进入图形化配置界面。
这个插件是给 C/C++ 提供编辑支持的,如高亮、格式化等,但实际编译需要进一步配置下面两个文件。
这里配置了两个,前者是 C++ 编译器(名字设置为 Win32 ,表示 Windows 系统默认配置)、后者是C编译器。
如果要使用 C 需要手动切换 Win32-C 配置,可以在图形化界面切换。
{ "configurations": [ { "name": "Win32", "includePath": [ "${workspaceFolder}\\**" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "windowsSdkVersion": "10.0.19041.0", "compilerPath": "E:/MYPROGRAM/ENV/MSYS2/msys64/mingw64/bin/g++.exe", "cStandard": "c17", "cppStandard": "c++17", "intelliSenseMode": "windows-gcc-x64" }, { "name": "Win32-C", "includePath": [ "${workspaceFolder}\\**" ], "defines": [ "_DEBUG", "UNICODE", "_UNICODE" ], "compilerPath": "E:/MYPROGRAM/ENV/MSYS2/msys64/mingw64/bin/gcc.exe", "cStandard": "c17", "cppStandard": "c++17", "intelliSenseMode": "windows-gcc-x64" } ], "version": 4 }
tasks.json
任务配置,配置编译用到的程序,如 gcc、g++。
这里只配置了 g++ ,但能编译大部分 C 的文件。
配置完后,对代码文件 Ctrl+Shift+B 就可以编译了。
{ "tasks": [ { "type": "cppbuild", "label": "C/C++: g++.exe 生成活动文件", "command": "E:\\MYPROGRAM\\ENV\\MSYS2\\msys64\\mingw64\\bin\\g++.exe", "args": [ "-fdiagnostics-color=always", "-g", // "-Wall", "${file}", "-o", "${fileDirname}\\${fileBasenameNoExtension}.exe" ], "options": { "cwd": "${fileDirname}" }, "problemMatcher": [ "$gcc" ], "presentation": { "echo": true, "reveal": "silent", "panel": "shared", "showReuseMessage": false, "clear": false }, "group": { "kind": "build", "isDefault": true }, "detail": "调试器生成的任务。" } ], "version": "2.0.0" }
launch.json
配置启动链,前者 C/CPP 编译+运行,后者 C/CPP 编译+调试 。
F5 启动(启动最近启动的模式),也可以到 Run 界面手动开启。
{ "configurations": [ { "name": "CPP启动(win)", "type": "cppvsdbg", "request": "launch", "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", "args": [ "/C", "${fileDirname}\\${fileBasenameNoExtension}.exe", "&", "pause" ], "stopAtEntry": false, "cwd": "${fileDirname}", "environment": [], "preLaunchTask": "C/C++: g++.exe 生成活动文件", "console": "externalTerminal" }, { "name": "CPP启动(gdb)", "type": "cppdbg", "request": "launch", "program": "${fileDirname}\\${fileBasenameNoExtension}.exe", "args": [], "stopAtEntry": false, "cwd": "${fileDirname}", "environment": [], "MIMode": "gdb", "miDebuggerPath": "E:\\MYPROGRAM\\ENV\\MSYS2\\msys64\\mingw64\\bin\\gdb.exe", "preLaunchTask": "C/C++: g++.exe 生成活动文件", "externalConsole": true, "setupCommands": [ { "description": "为 gdb 启用整齐打印", "text": "-enable-pretty-printing", "ignoreFailures": true }, { "description": "将反汇编风格设置为 Intel", "text": "-gdb-set disassembly-flavor intel", "ignoreFailures": true } ] } ], "version": "2.0.0" }
配置 C/CPP 插件的代码格式化
现在 C/CPP 集成了 clang-format 引擎和 vcFormat 引擎。
前者需要自己写一个 .clang-format
的 yaml 文件 ,后者在插件里即可调整。
为了自动格式化,首先要把设置->文本编辑器中的Format On Save打开。
对于 vcFormat 引擎,只需要在 C/CPP 插件中的 Formatting 选项选择 vcFormat 即可,在插件里面配置关于格式化的选项即可。
对于 clang-format 引擎,将写好的 yaml 文件扔进项目根目录下。
.clang-format
# 详情见 https://clang.llvm.org/docs/ClangFormatStyleOptions.html --- Language: Cpp # BasedOnStyle: Google # 访问声明符缩进偏移 AccessModifierOffset: -4 # 对齐开括号(圆括号、方括号、尖括号) AlignAfterOpenBracket: BlockIndent # 对齐结构休数组初始化 AlignArrayOfStructures: Right # 连续赋值时,对齐所有等号 AlignConsecutiveAssignments: false # 连续设置位域时,对齐所有冒号 AlignConsecutiveBitFields: false # 连续声明时,对齐所有声明的变量名 AlignConsecutiveDeclarations: false # 连续宏定义时,对齐所有定义 AlignConsecutiveMacros: false # 连续短 case 分支时,case 体的对齐方式 # AlignConsecutiveShortCaseStatements: # Enabled: false # 对齐续行符(\): AlignEscapedNewlines: Right # 对齐二元/三元元表达式中的操作数 AlignOperands: Align # 对齐连续行的行内注释 AlignTrailingComments: Always # 允许函数实参或花括号初始化不够放时整体放在下一行 AllowAllArgumentsOnNextLine: false # 允许函数形参不够放时整体放在下一行 AllowAllParametersOfDeclarationOnNextLine: false # 允许 noexcept 前换行 AllowBreakBeforeNoexceptSpecifier: Never # 允许短的语句块放在同一行 AllowShortBlocksOnASingleLine: Always # 允许短的 case 表达式放在同一行 AllowShortCaseExpressionOnASingleLine: true # 允许短的 case 标签放在同一行 AllowShortCaseLabelsOnASingleLine: true # 允许短的组合 require 放在同一行 AllowShortCompoundRequirementOnASingleLine: true # 允许短的 enum 放在同一行 AllowShortEnumsOnASingleLine: true # 允许短的函数放在同一行 AllowShortFunctionsOnASingleLine: All # 允许短的判断语句放在同一行 AllowShortIfStatementsOnASingleLine: AllIfsAndElse # 允许短的 lambda 放在一行中 AllowShortLambdasOnASingleLine: All # 允许短的循环语句块放在同一行 AllowShortLoopsOnASingleLine: true # 在多行字符串字面量的第一行前是否强制换行 AlwaysBreakBeforeMultilineStrings: false # 是否一行可以放多个函数实参 BinPackArguments: true # 是否一行可以放多个函数形参 BinPackParameters: true # 域定义冒号前后空格设置 BitFieldColonSpacing: None # 花括号前后的强制换行和缩进风格 BraceWrapping: # 若在...后,则前面换行 AfterCaseLabel: false AfterClass: false AfterControlStatement: Never AfterEnum: false AfterFunction: false AfterNamespace: false AfterStruct: false AfterUnion: false AfterExternBlock: false # 若在...前,则后面换行 BeforeCatch: true BeforeElse: true BeforeLambdaBody: false BeforeWhile: false # 额外缩进 IndentBraces: false # 空花括号体是否强制分行 SplitEmptyFunction: false SplitEmptyRecord: false SplitEmptyNamespace: false # 花括号体初始化内部缩进,不设置则与公共缩进一致 # BracedInitializerIndentWidth: 4 # 邻接的字符串字面量之间是否强制换行 BreakAdjacentStringLiterals: false # Attributes 后的强制换行风格 BreakAfterAttributes: Always # 返回类型后是否换行,根据惩罚系数 # BreakAfterReturnType: Automatic # 换行时,二元操作符是否在新的一行 BreakBeforeBinaryOperators: None # 花括号的强制换行风格,具体值可参考上方文档 BreakBeforeBraces: Custom # 概念声明的强制换行风格 BreakBeforeConceptDeclarations: Always # 换行时,三元操作符是否在新的一行 BreakBeforeTernaryOperators: false # 二元操作符是否强制换行 BreakBinaryOperations: Never # 构造函数列表强制换行风格,不设置就不换行 # BreakConstructorInitializers: AfterColon # 函数定义形参是否强制换行 BreakFunctionDefinitionParameters: false # 继承列表换行风格 BreakInheritanceList: AfterColon # 字面字符串是否强制分行 BreakStringLiterals: true # 模板函数声明强制换行风格 BreakTemplateDeclarations: Yes # 代码列字符上限 ColumnLimit: 0 # 命名空间是否合并为一行 CompactNamespaces: false # 构造函数初始化列表缩进 ConstructorInitializerIndentWidth: 4 # 续行缩进 ContinuationIndentWidth: 4 # C++11 的统一初始化列表大括号风格,即是否去除大括号内部两侧空格 Cpp11BracedListStyle: false # 是否开启文件分析, 根据文件中的*/&使用情况更新clang-format设定, 在无法决定时, 使用PointerAlignment代替 DerivePointerAlignment: false # 是否禁用格式化 DisableFormat: false # 访问限定后是否添加空行 EmptyLineAfterAccessModifier: Never # 访问限定前是否要求空行 EmptyLineBeforeAccessModifier: LogicalBlock # 实验性的自动检测同行并进行操作 ExperimentalAutoDetectBinPacking: false # 是否强制在短的 namespace 结尾增加 // namespace xxx FixNamespaceComments: false # include 代码块格式化风格,如果 SortIncludes 开启 IncludeBlocks: Preserve # 访问限定是否缩进 IndentAccessModifiers: false # case 体是否缩进 IndentCaseBlocks: true # case 标签是否缩进 IndentCaseLabels: false # goto 标签是否缩进 IndentGotoLabels: true # 预处理指示是否缩进 IndentPPDirectives: None # extern "C" 是否缩进 IndentExternBlock: AfterExternBlock # 模板 require 是否缩进 IndentRequiresClause: true # 缩进宽度 IndentWidth: 4 # 返回值和函数名不同行时,是否缩进 IndentWrappedFunctionNames: false # 是否在代码块中(if/else/for/do/while)强制插入大括号 InsertBraces: false # 是否插入一个空行在文件尾部 InsertNewlineAtEOF: true # 是否强制插入拖尾的逗号 InsertTrailingCommas: None # 代码块开始前有一个空行 KeepEmptyLinesAtTheStartOfBlocks: false # lambda 函数体缩进风格 LambdaBodyIndentation: Signature # 代码块间空行上限 MaxEmptyLinesToKeep: 1 # namespace 内的缩进风格 NamespaceIndentation: All # 构造函数初始化列表换行风格 PackConstructorInitializers: NextLine # 预处理对齐宽度 PPIndentWidth: -1 # # 罚分设定(根据你的"违规"值选择罚分少的) # PenaltyBreakAssignment: 2 # PenaltyBreakBeforeFirstCallParameter: 19 # PenaltyBreakComment: 300 # PenaltyBreakFirstLessLess: 120 # PenaltyBreakOpenParenthesis: 10000 # PenaltyBreakString: 1000 # PenaltyBreakTemplateDeclaration: 10 # PenaltyExcessCharacter: 1000000 # PenaltyReturnTypeOnItsOwnLine: 60 # PenaltyIndentedWhitespace: 0 # 指针符对齐 PointerAlignment: Right # 修饰符对齐(const/volatile) QualifierAlignment: Leave # 引用符对齐 ReferenceAlignment: Pointer # 是否允许格式化注释 ReflowComments: true # 是否按 LLVM 规则移除多余的大括号对 RemoveBracesLLVM: false # 是否移除多余的小括号对 RemoveParentheses: Leave # 是否移除花括号对后多余的分号 RemoveSemicolon: false # 模板中的require语句位置 RequiresClausePosition: OwnLine RequiresExpressionIndentation: OuterScope # 不同定义块之间加空行的风格 SeparateDefinitionBlocks: Leave # 短的命名空间的行数 ShortNamespaceLines: 0 # 是否对 #include 排序 SortIncludes: Never # 是否对 using 排序 SortUsingDeclarations: false # C风格强制转换类型符后面是否加空格 SpaceAfterCStyleCast: false # 逻辑非操作后面是否加空格 SpaceAfterLogicalNot: false # template 关键字后面是否加空格 SpaceAfterTemplateKeyword: false # 指针修饰词的前后空格风格 SpaceAroundPointerQualifiers: Default # 赋值语句操作符前是否添加空格 SpaceBeforeAssignmentOperators: true # case 语句前是否增加空格 SpaceBeforeCaseColon: false # c++11的统一初始化列表的大括号前是否添加空格 SpaceBeforeCpp11BracedList: false # 构造函数初始化列表的冒号前是否加空格 SpaceBeforeCtorInitializerColon: false # 继承列表的冒号前是否加空格 SpaceBeforeInheritanceColon: true # 圆括号前是否增加空格 SpaceBeforeParens: ControlStatements # 基于范围的循环前是否增加空格 SpaceBeforeRangeBasedForLoopColon: true # 方括号前是否加空格 SpaceBeforeSquareBrackets: false # 空语句块内是否加空格 SpaceInEmptyBlock: false # 行内注释前的空格数 SpacesBeforeTrailingComments: 1 # 角括号内两侧是否增加空格 SpacesInAngles: Never # 行内注释后的空格数量范围 SpacesInLineCommentPrefix: Minimum: 1 Maximum: 1 # 圆括号内两侧是否加空格 SpacesInParentheses: false # 方括号内两侧是否加空格 SpacesInSquareBrackets: false # C++标准 Stardard: Latest # Tab宽度 TabWidth: 4 # Tab使用 UseTab: Never
配置 CPP 代码模板
在设置->用户代码片段->选择Cpp文件->进行如下类似自定义 。
prefix
用于输入前缀匹配,之后只要在文本中输入这个就可以将文本替换。
{ "ONE_DATA_ACM_MODLE": { "prefix": "acm1", "body": [ "#include <bits/stdc++.h>", "using namespace std;", "using ll = long long;", "", "int main() {", "\tstd::ios::sync_with_stdio(0), std::cin.tie(0), std::cout.tie(0);", "\t", "\t", "\treturn 0;", "}" ], "description": "Init an ONE_DATA_ACM_MODLE." }, "T_DATA_ACM_MODLE": { "prefix": "acmT", "body": [ "#include <bits/stdc++.h>", "using namespace std;", "using ll = long long;", "", "bool solve() {", "\t", "\treturn true;", "}", "", "int main() {", "\tstd::ios::sync_with_stdio(0), std::cin.tie(0), std::cout.tie(0);", "\tint t = 1;", "\tcin >> t;", "\twhile (t--) {", "\t\tif (!solve()) cout << -1 << '\\n';", "\t}", "\treturn 0;", "}", ], "description": "Init an T_DATA_ACM_MODLE." } }
输出中文到本地终端的乱码问题
注意编程环境默认是 UTF-8
编码,而中国计算机终端使用的是 GBK
编码,这样会导致在环境里的中文到计算机终端会乱码,而计算机自身保存的中文到环境也会乱码。
可以通过修改文件的编码解决这个问题。
但我仍旧建议使用 UTF-8
编码,为了避免未来可能出现的麻烦。
插件介绍
通用:
- 简体中文:让 VS Code 说中国话 。
- Better Comments:可以配置个性化注释。
- Code Runner:懒人必备,一键运行(环境得配置好)。
- Doxygen Documentation Generator:文档生成器。
- Error Lens:真神,实时显示可能的编译错误。
- Material Icon Theme:更多图标,如文件夹之类的。
- Rainbow CSV:更好的 CSV 查看器。
- VS Code Counter:代码计数器,看看你写了多少代码。
C/C++:
- C/C++ 系列:支持 C/C++ 高亮、格式化、特色主题等。
- Better C++ Syntax:更适合 C++ 的主题。
Python:
- autopep8:一个格式化引擎。
- Jupyter系列:在 VS Code 内编辑 ipynb 文件(相当于集成了 notebook 的功能)。
- Python 系列:支持 Python 高亮等功能。
Latex:
- LaTeX Workshop:支持编写 Latex 的相关功能(环境还得自己配置)。
用户设置
包括插件和编辑器等全局配置。
{ "terminal.integrated.defaultProfile.windows": "Command Prompt", "workbench.colorTheme": "Monokai", "workbench.iconTheme": "material-icon-theme", "editor.linkedEditing": true, "editor.formatOnType": true, "editor.formatOnSave": true, "git.autoRepositoryDetection": false, "git.enabled": false, "[cpp]": { "editor.defaultFormatter": "ms-vscode.cpptools" }, "[python]": { "editor.defaultFormatter": "ms-python.autopep8" }, "code-runner.runInTerminal": true, "C_Cpp.formatting": "vcFormat", "C_Cpp.vcFormat.indent.lambdaBracesWhenParameter": false, "C_Cpp.vcFormat.newLine.beforeOpenBrace.block": "sameLine", "C_Cpp.vcFormat.newLine.beforeOpenBrace.function": "sameLine", "C_Cpp.vcFormat.newLine.beforeOpenBrace.lambda": "sameLine", "C_Cpp.vcFormat.newLine.beforeOpenBrace.namespace": "sameLine", "C_Cpp.vcFormat.newLine.beforeOpenBrace.type": "sameLine", "C_Cpp.vcFormat.newLine.closeBraceSameLine.emptyFunction": true, "C_Cpp.vcFormat.newLine.closeBraceSameLine.emptyType": true, "C_Cpp.vcFormat.space.pointerReferenceAlignment": "right", "markdown-preview-enhanced.previewTheme": "monokai.css", "vetur.format.enable": false, "better-comments.tags": [ { "tag": "!", "color": "#FF2D00", "strikethrough": false, "underline": false, "backgroundColor": "transparent", "bold": false, "italic": false }, { "tag": "?", "color": "#3498DB", "strikethrough": false, "underline": false, "backgroundColor": "transparent", "bold": false, "italic": false }, { "tag": "//", "color": "#474747", "strikethrough": true, "underline": false, "backgroundColor": "transparent", "bold": false, "italic": false }, { "tag": "todo", "color": "#FF8C00", "strikethrough": false, "underline": false, "backgroundColor": "transparent", "bold": false, "italic": false }, { "tag": "*", "color": "#98C379", "strikethrough": false, "underline": false, "backgroundColor": "transparent", "bold": false, "italic": false }, { "tag": "/", "color": "#FF66AC", "strikethrough": false, "underline": false, "backgroundColor": "transparent", "bold": true, "italic": false } ], "latex-workshop.formatting.latex": "latexindent", "latex-workshop.latex.autoBuild.run": "never", "latex-workshop.latex.recipe.default": "lastUsed", "latex-workshop.latex.tools": [ { "name": "pdflatex", "command": "pdflatex", "args": [ "-synctex=1", "-interaction=nonstopmode", "-file-line-error", "-outdir=%OUTDIR%", "%DOC%" ], "env": {} }, { "name": "xelatex", "command": "xelatex", "args": [ "-synctex=1", "-interaction=nonstopmode", "-file-line-error", "-outdir=%OUTDIR%", "%DOC%" ], "env": {} }, { "name": "bibtex", "command": "bibtex", "args": [ "%DOCFILE%" ], "env": {} } ], "latex-workshop.latex.recipes": [ { "name": "xelatex", "tools": [ "xelatex" ] }, { "name": "pdflatex", "tools": [ "pdflatex" ] }, { "name": "bibtex", "tools": [ "bibtex" ] }, { "name": "pdflatex -> bibtex -> pdflatex * 2", "tools": [ "pdflatex", "bibtex", "pdflatex", "pdflatex" ] }, { "name": "xelatex -> bibtex -> xelatex * 2", "tools": [ "xelatex", "bibtex", "xelatex", "xelatex" ] } ], }
本文来自博客园,作者:空白菌,转载请注明原文链接:https://www.cnblogs.com/BlankYang/p/16286979.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧