VSCode C++ on WSL2 配置
在Windows系统上通过wsl构建Linux开发环境,用VSCode开发C++程序。分步骤配置过程。

VSCode C++ on WSL2 配置



一、安装wsl2(Windows11)

官方指导:https://docs.microsoft.com/en-us/windows/wsl/install

  1. 确保windwos版本:
  • Windows 10 version 2004 and higher (Build 19041 and higher) or Windows 11
  1. 以管理员运行:PowerShell as Administrator
wsl --install

注意: 上述命令适用于完全没安装过wsl的新机器。如果上述命令运行提示问题,先用 wsl --list --online 查询可安装的distros,wsl --install -d <DistroName> 指定一个distro安装。


以下为分步安装法(过时了!):

  1. 管理员运行:PowerShell as Administrator
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
  1. 按下Win + R,调出"运行"窗口。输入指令appwiz.cpl,调出"启动或关闭 Windows 功能",启动:

    • windows虚拟机监控程序平台
    • 适用于Linux的windows子系统
    • 虚拟机平台
  2. 管理员运行:PowerShell as Administrator

dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
  1. 下载安装package: WSL2 Linux kernel update package for x64 machines

  2. 管理员运行:PowerShell as Administrator

wsl --set-default-version 2
  1. 检查安装是否正确:管理员运行:PowerShell as Administrator
wsl --list --verbose

安装后

  • Windows更新,高级选项中开启"接收其他windows产品的更新"。
  • 管理员运行:PowerShell as Administrator
    wsl --updatewsl --shutdown
  • Microsoft Store中安装Ubuntu和Windows Terminal
  • 运行ubuntu设置管理员账号。
  • Windows中挂载wsl系统文件:\\wsl$

二、Ubuntu设置

$ sudo apt-get update
$ sudo apt-get upgrade

$ sudo apt-get install build-essential gdb cmake gcc
$ sudo apt-get install git sqlite3 libsqlite3-dev libncurses-dev
$ sudo apt-get install libgsl-dev libatlas-base-dev

$ sudo apt-get install gedit

补充:后续更新Ubuntu大版本

$ sudo apt update
$ sudo apt upgrade
$ sudo apt dist-upgrade

$ sudo apt install update-manager-core    # 应该已经有了,不需安装

$ sudo vim /etc/update-manager/release-upgrades    # 修改Prompt=lts或者normal

$ sudo do-release-upgrade -d    # -d 代表可以安装development release

$ lsb_release -a    # 检查版本

三、VSCode安装和设置

  1. 安装: 官网:https://code.visualstudio.com/

  2. 运行,提示发现wsl,安装remote-wsl插件

  3. Ubuntu新建项目文件夹并运行:

$ cd ~
$ mkdir VSCodeProjects
$ cd VSCodeProjects
$ mkdir test
$ cd test
$ code .
  1. 注意vscode左下角,显示”><WSL:Ubuntu“,在此状态下安装插件。
  2. 插件:

Local:

  • Better C++ Syntax
  • C/C++ Themes
  • TODO Highlight
  • WSL(此时应该已经安装,且带星显示)

WSL:

  • C/C++
  • C++ Extension Pack
  • indent-rainbow
  • Markdown Preview Github
  • GitHub Copilot
  • GitHub Copilot Chat

四、VSCode的使用

(一)配置文件

VS Code provides two different scopes for settings:

  • User Settings - Settings that apply globally to any instance of VS Code you open.
  • Workspace Settings - Settings stored inside your workspace and only apply when the workspace is opened.
    注意:Workspace settings override user settings.

(二)常用快捷键

( 官方常用快捷键pdf:Windows版本Mac版本Linux版本

  1. Command Palette:Access all available commands based on your current context.
  • Keyboard Shortcut: Ctrl+Shift+p
  1. 集成的Terminal: Ctrl+`

  2. 显示/隐藏Sidebar:Ctrl+b

  3. 显示/隐藏Panel:Ctrl+j

  4. 切换editors:Ctrl+1, Ctrl+2, Ctrl+3

  5. Go to Symbol in File

  • Keyboard Shortcut: Ctrl+Shift+o
  • (group the symbols by kind) @:
  1. Go to Symbol in Workspace
  • Keyboard Shortcut: Ctrl+t
  1. Select current line:Ctrl+l

  2. Multi cursor:mouse select

  • Keyboard Shortcut: Alt+Click
  1. Multi cursor:add additional cursors to all occurrences of the current selection with
  • Keyboard Shortcut: Ctrl+Shift+l
  1. Fast scrolling:5X speed multiplier:Pressing the Alt key

  2. Move line up and down:Alt+Up or Alt+Down

  3. Go to Definition定义

  • Select a symbol then type F12.
  • Ctrl+click
  1. 跳转后返回:Alt+左
  2. Peek窥视定义
  • 鼠标悬停按住Ctrl
  • Select a symbol then type Alt+F12
  1. Go to Implementation
  • Select a symbol then type Ctrl+F12
  1. Go to References
  • Select a symbol then type Shift+F12
  1. Show All References List of All Files in Project
  • Select a symbol then type Shift+Alt+F12
  1. Find and Replace in File:Ctrl+f

  2. Search across files:Ctrl+Shift+f

  3. Markdown Preview(.md file):Ctrl+Shift+v (再拖拽分屏)

(三)settings.json范例

2024-02-23 (VSCode1.86.2)

{
    "update.mode": "manual",
    "telemetry.telemetryLevel": "off",
    "remote.downloadExtensionsLocally": true,
    "window.confirmBeforeClose": "always",
    "window.autoDetectHighContrast": false,
    "window.commandCenter": false,

    "files.autoGuessEncoding": true,
    "files.hotExit": "off",
    "files.insertFinalNewline": true,
    "files.trimTrailingWhitespace": true,
    "workbench.editor.highlightModifiedTabs": true,
    "workbench.editor.openPositioning": "last",
    "workbench.experimental.cloudChanges.autoStore": "onShutdown",
    "workbench.sideBar.location": "right",
    "workbench.list.smoothScrolling": true,
    "workbench.activityBar.location": "top",
    "workbench.tree.enableStickyScroll": true,
    "workbench.colorTheme": "Visual Studio 2017 Light - C++",
    "workbench.colorCustomizations": {
        "statusBar.background": "#dedede",
        "statusBar.foreground": "#757575",
        "activityBar.background": "#dedede",
        "activityBar.foreground": "#757575",
        "statusBarItem.remoteBackground": "#ffffff",
        "statusBarItem.remoteForeground": "#017717",

        "terminal.background":"#FFFFFF",
        "terminal.foreground":"#4D4D4C",
        "terminalCursor.background":"#4D4D4C",
        "terminalCursor.foreground":"#4D4D4C",
        "terminal.ansiBlack":"#FFFFFF",
        "terminal.ansiBlue":"#4271AE",
        "terminal.ansiBrightBlack":"#8E908C",
        "terminal.ansiBrightBlue":"#4271AE",
        "terminal.ansiBrightCyan":"#3E999F",
        "terminal.ansiBrightGreen":"#718C00",
        "terminal.ansiBrightMagenta":"#8959A8",
        "terminal.ansiBrightRed":"#C82829",
        "terminal.ansiBrightWhite":"#1D1F21",
        "terminal.ansiBrightYellow":"#EAB700",
        "terminal.ansiCyan":"#3E999F",
        "terminal.ansiGreen":"#718C00",
        "terminal.ansiMagenta":"#8959A8",
        "terminal.ansiRed":"#C82829",
        "terminal.ansiWhite":"#4D4D4C",
        "terminal.ansiYellow":"#EAB700"
    },

    "editor.fontFamily": "'Ubuntu Mono derivative Powerline'",
    "editor.fontSize": 16,
    // "editor.inlineSuggest.enabled": true,
    // "editor.inlineCompletionsAccessibilityVerbose": true,
    "editor.detectIndentation": false,
    "editor.renderWhitespace": "trailing",
    "editor.copyWithSyntaxHighlighting": false,
    "editor.dropIntoEditor.enabled": false,
    "editor.multiCursorLimit": 50,
    "editor.renderLineHighlight": "all",
    "editor.scrollbar.horizontal": "hidden",
    "editor.smartSelect.selectLeadingAndTrailingWhitespace": false,
    "editor.cursorWidth": 2,
    "editor.find.cursorMoveOnType": false,
    "editor.suggestSelection": "recentlyUsedByPrefix",
    "editor.unicodeHighlight.nonBasicASCII": false,
    "editor.largeFileOptimizations": false,
    "editor.links": false,
    "editor.lineNumbers": "off",
    "editor.smoothScrolling": true,
    "editor.scrollbar.verticalScrollbarSize": 6,
    "editor.minimap.showSlider": "always",
    "editor.minimap.size": "fit",
    "editor.minimap.maxColumn": 60,
    "editor.suggest.preview": true,
    "editor.quickSuggestions": {
        "strings": "on"
    },
    "editor.wordBasedSuggestions": "off",
    "editor.acceptSuggestionOnEnter": "off",
    "editor.tabCompletion": "on",
    "editor.formatOnType": false,
    "editor.formatOnPaste": false,
    "editor.scrollBeyondLastLine": false,
    "editor.stickyTabStops": true,
    "editor.rulers": [80],
    "editor.bracketPairColorization.independentColorPoolPerBracketType": true,
    "editor.definitionLinkOpensInPeek": true,
    "editor.foldingMaximumRegions": 500,
    "editor.accessibilityPageSize": 500,
    "editor.dragAndDrop": false,
    "editor.guides.bracketPairs": true,
    "editor.occurrencesHighlight": "multiFile",
    "editor.suggest.shareSuggestSelections": true,
    "editor.suggest.localityBonus": true,
    "editor.mouseWheelZoom": true,

    "explorer.enableDragAndDrop": false,
    "problems.showCurrentInStatus": true,
    "search.smartCase": true,
    "search.useParentIgnoreFiles": true,

    "zenMode.hideStatusBar": false,
    "zenMode.silentNotifications": false,

    "terminal.external.windowsExec": "wt.exe",
    "terminal.integrated.defaultProfile.linux": "bash",
    "terminal.integrated.shellIntegration.enabled": true,
    "terminal.integrated.scrollback": 5000,
    "terminal.integrated.copyOnSelection": true,
    "terminal.integrated.altClickMovesCursor": false,

    "todohighlight.isEnable": true,
    "todohighlight.include": [
        "**/*.h",
        "**/*.cpp",
        "**/*.c",
        "**/*.json",
    ],
    "todohighlight.keywords": [
        "TODO",
        " todo",
        "//todo",
        "// todo",
        " LATER",
        " later",
        " FIX",
        " fix",
    ],
    "indentRainbow.ignoreLinePatterns": [
        "/[ \t]* [*]/g",
        "/[ \t]+[/]{2}/g"
    ],

    "C_Cpp.default.intelliSenseMode": "linux-gcc-x64",
    "C_Cpp.default.cppStandard": "gnu++20",
    "C_Cpp.default.cStandard": "gnu17",
    "C_Cpp.experimentalFeatures": "enabled",
    "C_Cpp.inlayHints.referenceOperator.enabled": true,
    "C_Cpp.inlayHints.referenceOperator.showSpace": true,
    "C_Cpp.inlayHints.parameterNames.hideLeadingUnderscores": false,
    "C_Cpp.autocompleteAddParentheses": true,
    "C_Cpp.clang_format_style": "{ BasedOnStyle: Google, IndentWidth: 4, ColumnLimit: 0}",
    "C_Cpp.clang_format_fallbackStyle": "{ BasedOnStyle: Google, IndentWidth: 4, ColumnLimit: 0}",
    "C_Cpp.formatting": "vcFormat",
    "C_Cpp.vcFormat.wrap.preserveBlocks": "allOneLineScopes",
    "C_Cpp.vcFormat.indent.braces": true,
    "C_Cpp.vcFormat.indent.caseContentsWhenBlock": true,
    "C_Cpp.vcFormat.indent.preserveComments": true,
    "C_Cpp.vcFormat.indent.caseLabels": true,
    "C_Cpp.vcFormat.indent.preserveWithinParentheses": true,
    "C_Cpp.vcFormat.indent.lambdaBracesWhenParameter": false,
    "C_Cpp.vcFormat.indent.namespaceContents": false,
    "C_Cpp.vcFormat.newLine.beforeElse": false,
    "C_Cpp.vcFormat.newLine.beforeOpenBrace.block": "newLine",
    "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.beforeWhileInDoWhile": true,
    "C_Cpp.vcFormat.newLine.closeBraceSameLine.emptyFunction": true,
    "C_Cpp.vcFormat.newLine.closeBraceSameLine.emptyType": true,
    "C_Cpp.vcFormat.newLine.scopeBracesOnSeparateLines": true,
    "C_Cpp.vcFormat.space.afterCastCloseParenthesis": true,
    "C_Cpp.vcFormat.space.withinCastParentheses": true,
    "C_Cpp.vcFormat.space.aroundAssignmentOperator": "ignore",
    "C_Cpp.vcFormat.space.aroundBinaryOperator": "ignore",
    "C_Cpp.vcFormat.space.aroundTernaryOperator": "ignore",
    "C_Cpp.codeAnalysis.runAutomatically": true,
    "C_Cpp.codeAnalysis.clangTidy.enabled": true,
    "C_Cpp.codeAnalysis.clangTidy.useBuildPath": true,
    "C_Cpp.codeAnalysis.clangTidy.codeAction.showClear": "None",
    "C_Cpp.codeAnalysis.clangTidy.codeAction.showDisable": false,
    "C_Cpp.codeAnalysis.updateDelay": 100,
    "C_Cpp.intelliSenseUpdateDelay": 1000,
    "C_Cpp.doxygen.generatedStyle": "//!",
    "C_Cpp.loggingLevel": "Warning",

    "git.enableSmartCommit": true,
    "git.openRepositoryInParentFolders": "always",

    "scm.alwaysShowRepositories": true,
    "cmake.configureOnOpen": true,
    "github.copilot.chat.localeOverride": "en",
    "security.workspace.trust.untrustedFiles": "newWindow",

    // "http.proxy": "http://172.24.16.1:7890",
}

最后修改于 2024-02-22