VSCODE指南

(本文内容由AI生成,相关指导未实测)

安装

1.1 下载与安装

  1. 下载地址:访问 VS Code 官网

  2. 版本选择

    • Windows:推荐下载 User Installer(用户安装版)

    • macOS:直接下载 .dmg 文件

    • Linux:提供 .deb(Ubuntu/Debian)和 .rpm(Fedora/RHEL)包

  3. 安装步骤

    • Windows:运行安装程序,建议勾选以下选项:

      • ✅ 添加到 PATH(便于命令行使用)

      • ✅ 注册为支持的文件类型的编辑器

      • ✅ 添加到右键菜单

    • macOS:拖拽到应用程序文件夹

    • Linux:使用包管理器安装或双击安装包

设置

2.1 打开设置面板

  • 方法1:文件 → 首选项 → 设置(或快捷键 Ctrl + , / Cmd + ,

  • 方法2:命令面板输入 "Preferences: Open Settings"(Ctrl + Shift + P

2.2 常用基础设置

// settings.json 配置示例
{
    // 编辑器设置
    "editor.fontSize": 14,
    "editor.fontFamily": "'Cascadia Code', Consolas, 'Courier New', monospace",
    "editor.lineHeight": 1.6,
    "editor.tabSize": 4,
    "editor.insertSpaces": true,
    "editor.wordWrap": "on",
    
    // 文件设置
    "files.autoSave": "afterDelay",
    "files.autoSaveDelay": 1000,
    "files.exclude": {
        "**/.git": true,
        "**/.DS_Store": true,
        "**/node_modules": true
    },
    
    // 工作区
    "workbench.colorTheme": "Horizon Extended Theme",
    "workbench.iconTheme": "vs-seti",
    
    // 终端设置
    "terminal.integrated.fontSize": 13,
    "terminal.integrated.defaultProfile.windows": "PowerShell",
    "terminal.integrated.defaultProfile.linux": "bash",
    "terminal.integrated.defaultProfile.osx": "zsh"
}

2.3 键盘快捷键自定义

  1. 文件 → 首选项 → 键盘快捷方式(或 Ctrl + K Ctrl + S

  2. 点击右上角打开键盘快捷方式JSON文件

  3. 添加自定义绑定,例如:

[
    {
        "key": "ctrl+shift+/",
        "command": "editor.action.blockComment",
        "when": "editorTextFocus"
    },
    {
        "key": "alt+up",
        "command": "editor.action.moveLinesUpAction"
    }
]

使用

3.1 基础操作

  • 打开项目:文件 → 打开文件夹(Ctrl + K Ctrl + O

  • 命令面板Ctrl + Shift + P(所有功能的快捷入口)

  • 侧边栏切换Ctrl + B

  • 集成终端:`Ctrl + ``

  • 分屏编辑Ctrl + \ 或右键标签页选择拆分

3.2 编辑技巧

  1. 多光标操作

    • Alt + 点击:添加多个光标

    • Ctrl + Alt + ↑/↓:上下添加光标

    • Ctrl + D:选中下一个相同词

  2. 代码导航

    • Ctrl + P:快速打开文件

    • Ctrl + T:搜索所有符号

    • F12:转到定义

    • Alt + ←/→:导航历史

  3. 版本控制

    • 侧边栏源代码管理图标

    • Ctrl + Shift + G:打开Git面板

    • 支持提交、推送、拉取、分支管理

3.3 调试功能

  1. 点击左侧调试图标或 Ctrl + Shift + D

  2. 创建 launch.json 配置文件

  3. 支持断点、变量检查、调用堆栈

  4. 调试控制台:查看程序输出

插件

4.1 Bracket Pair Colorization Toggler

功能:彩色括号匹配,便于识别代码块范围

安装后设置

{
    "bracket-pair-colorizer-2.colors": [
        "Gold",
        "Orchid",
        "LightSkyBlue"
    ],
    "bracket-pair-colorizer-2.highlightActiveScope": true,
    "bracket-pair-colorizer-2.activeScopeCSS": [
        "borderStyle : solid",
        "borderWidth : 1px",
        "borderColor : {color}"
    ],
    "bracket-pair-colorizer-2.forceUniqueOpeningColor": true
}

使用方法

  • 自动生效,不同层级的括号会显示不同颜色

  • 点击括号可高亮匹配的对应括号

4.2 C/C++ 和 C/C++ Extension Pack

功能:完整的C/C++开发支持(IntelliSense、调试、代码导航)

安装步骤

  1. 搜索安装 "C/C++" (Microsoft)

  2. 搜索安装 "C/C++ Extension Pack"(包含扩展包)

配置设置

{
    "C_Cpp.default.cppStandard": "c++17",
    "C_Cpp.default.cStandard": "c11",
    "C_Cpp.default.intelliSenseMode": "windows-gcc-x64",
    "C_Cpp.default.compilerPath": "C:/mingw64/bin/g++.exe", // Windows
    "C_Cpp.default.compilerPath": "/usr/bin/g++", // Linux
    "C_Cpp.default.compilerPath": "/usr/bin/clang++", // macOS
    "C_Cpp.autocomplete": "default",
    "C_Cpp.codeAnalysis.clangTidy.enabled": true
}

创建配置文件

  1. 在项目根目录创建 .vscode 文件夹

  2. 创建 c_cpp_properties.json

{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**",
                "C:/mingw64/include"
            ],
            "defines": ["_DEBUG"],
            "compilerPath": "C:/mingw64/bin/g++.exe"
        }
    ],
    "version": 4
}

4.3 Chinese (Simplified) Language Pack

功能:VS Code界面汉化

使用方法

  1. 安装后按 Ctrl + Shift + P

  2. 输入 "Configure Display Language"

  3. 选择 "zh-cn"

  4. 重启VS Code生效

切换回英文

  • 命令面板输入 "Configure Display Language"

  • 选择 "en"

  • 重启VS Code

4.4 CMake Tools

功能:CMake项目集成支持

配置设置

{
    "cmake.configureOnOpen": true,
    "cmake.buildDirectory": "${workspaceFolder}/build",
    "cmake.generator": "Ninja", // 或 "Unix Makefiles"
    "cmake.buildBeforeRun": true,
    "cmake.options.statusBarVisibility": "visible"
}

使用流程

  1. 打开CMake项目

  2. 底部状态栏出现CMake工具条

  3. 选择Kit(编译器)

  4. 选择构建目标

  5. 点击状态栏的构建/调试按钮

4.5 Code Spell Checker

功能:代码拼写检查

配置设置

{
    "cSpell.userWords": [
        "namespace",
        "std",
        "unordered_map",
        "vector"
    ],
    "cSpell.enabled": true,
    "cSpell.enableFiletypes": [
        "cpp",
        "c",
        "python",
        "markdown"
    ],
    "cSpell.ignorePaths": [
        "node_modules",
        "build",
        "*.min.js"
    ],
    "cSpell.ignoreRegExpList": [
        "URLs",
        "HexValues"
    ]
}

使用方法

  • 拼写错误的单词会有波浪下划线

  • 右键点击可添加到词典或忽略

  • 创建项目专用词典:.cspell.json

4.6 CodeGeeX: AI Coding Assistant

功能:AI代码辅助(生成、解释、翻译)

设置配置

{
    "CodeGeeX.API Key": "your-api-key", // 如果需要
    "CodeGeeX.enableCodeGeneration": true,
    "CodeGeeX.enableCodeExplanation": true,
    "CodeGeeX.enableCodeTranslation": true,
    "CodeGeeX.language": "中文", // 或 "English"
    "CodeGeeX.generationMode": "inline" // 或 "panel"
}

使用方式

  1. 代码生成:注释描述功能,按 Ctrl + Enter 生成

  2. 代码解释:选中代码,右键选择 "Explain Code"

  3. 代码翻译:右键选择 "Translate Code"

  4. 问答模式:打开CodeGeeX侧边栏面板

4.7 highlight-words

功能:高亮显示选中的相同单词

配置设置

{
    "highlightwords.box": {
        "light": true,
        "backgroundColor": "#ff0000",
        "borderColor": "#ff0000"
    },
    "highlightwords.defaults": {
        "caseSensitive": true,
        "wholeWord": false
    },
    "highlightwords.colors": [
        "#FF0000",
        "#00FF00",
        "#0000FF",
        "#FFFF00"
    ]
}

使用方法

  • 双击选中单词,相同单词自动高亮

  • 状态栏显示高亮词数

  • 点击状态栏图标可清除高亮

4.8 Horizon Extended Theme

功能:美化主题

应用方法

  1. 安装后按 Ctrl + Shift + P

  2. 输入 "Preferences: Color Theme"

  3. 选择 "Horizon Extended"

  4. 如需修改配色,可编辑设置:

{
    "workbench.colorCustomizations": {
        "[Horizon Extended]": {
            "editor.background": "#1C1E26",
            "statusBar.background": "#16161C"
        }
    }
}

4.9 Office Viewer

功能:预览Office文档(Word、Excel、PowerPoint)

配置设置

{
    "office-viewer.previewInUntitledDocuments": true,
    "office-viewer.enableEdit": false,
    "office-viewer.autoOpen": true,
    "office-viewer.maxFileSize": 10485760 // 10MB
}

使用方法

  1. 在资源管理器中右键Office文件

  2. 选择 "Open with Office Viewer"

  3. 或直接双击打开(根据设置)

  4. 支持 .docx, .xlsx, .pptx 格式

工作区

5.1 项目特定设置

  1. 在项目根目录创建 .vscode 文件夹

  2. 创建 settings.json 仅对该项目生效

// .vscode/settings.json
{
    "files.exclude": {
        "build/": true,
        "bin/": true
    },
    "C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools"
}

5.2 推荐扩展列表

创建 .vscode/extensions.json

json

{
    "recommendations": [
        "ms-vscode.cpptools",
        "twxs.cmake",
        "streetsidesoftware.code-spell-checker",
        "ziyasal.vscode-open-in-github"
    ]
}

高级技巧

6.1 任务配置

创建 .vscode/tasks.json 自动化任务:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Build Project",
            "type": "shell",
            "command": "g++ -g ${file} -o ${fileDirname}/${fileBasenameNoExtension}",
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

6.2 代码片段

文件 → 首选项 → 配置用户代码片段:

{
    "C++ Header": {
        "prefix": "header",
        "body": [
            "#ifndef ${TM_FILENAME_BASE/(.*)/${1:/upcase}/}_H",
            "#define ${TM_FILENAME_BASE/(.*)/${1:/upcase}/}_H",
            "",
            "$0",
            "",
            "#endif // ${TM_FILENAME_BASE/(.*)/${1:/upcase}/}_H"
        ],
        "description": "Create C++ header guard"
    }
}

6.3 快捷键参考表

功能

Windows/Linux

macOS

命令面板

Ctrl+Shift+P

Cmd+Shift+P

快速打开

Ctrl+P

Cmd+P

查找文件

Ctrl+F

Cmd+F

替换

Ctrl+H

Cmd+H

保存所有

Ctrl+K S

Cmd+K S

格式化代码

Shift+Alt+F

Shift+Option+F

折叠代码

Ctrl+Shift+[

Cmd+Option+[

展开代码

Ctrl+Shift+]

Cmd+Option+]

从传统IDE迁移

(仅供参考,未经过实际验证)

环境准备与插件安装

1.1 基础安装包

# 所有用户必须安装的核心插件
code --install-extension ms-vscode.cpptools            # C/C++核心支持
code --install-extension ms-vscode.cpptools-extension-pack  # C/C++扩展包
code --install-extension ms-vscode.cmake-tools         # CMake支持
code --install-extension eamodio.gitlens               # Git增强
code --install-extension streetsidesoftware.code-spell-checker  # 拼写检查

1.2 按原IDE选择迁移包

原Keil MDK用户 → 嵌入式ARM开发

# ARM嵌入式开发插件包
code --install-extension marus25.cortex-debug          # ARM Cortex-M调试
code --install-extension ms-vscode.hexeditor           # Hex文件编辑器
code --install-extension dan-c-underwood.arm           # ARM汇编语法高亮
code --install-extension gruntfuggly.todo-tree         # TODO列表管理

原Eclipse CDT用户 → 跨平台开发

# 跨平台开发插件包
code --install-extension ms-vscode.makefile-tools      # Makefile支持
code --install-extension twxs.cmake                    # CMake语言支持
code --install-extension mhutchie.git-graph            # Git图形化
code --install-extension cschlosser.doxdocgen          # Doxygen文档生成

原Visual Studio用户 → Windows桌面开发

# Windows桌面开发插件包
code --install-extension ms-vscode.vscode-embedded-tools  # 嵌入式工具
code --install-extension ms-vscode.cpptools-extension-pack
code --install-extension visualstudioexptteam.vscodeintellicode  # AI智能提示

编译工具链配置

2.1 工具链路径配置

// .vscode/c_cpp_properties.json - 统一配置模板
{
    "configurations": [
        {
            "name": "Windows-MSVC",
            "includePath": [
                "${workspaceFolder}/**",
                "C:/Program Files (x86)/Windows Kits/10/Include/**"
            ],
            "defines": ["_DEBUG", "UNICODE"],
            "compilerPath": "C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Tools/MSVC/14.29.30133/bin/Hostx64/x64/cl.exe",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "windows-msvc-x64"
        },
        {
            "name": "Linux-GCC",
            "includePath": [
                "${workspaceFolder}/**",
                "/usr/include",
                "/usr/local/include"
            ],
            "defines": ["_DEBUG", "LINUX"],
            "compilerPath": "/usr/bin/g++",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "linux-gcc-x64"
        },
        {
            "name": "ARM-GCC",
            "includePath": [
                "${workspaceFolder}/**",
                "C:/Program Files (x86)/GNU Tools ARM Embedded/9 2019-q4-major/arm-none-eabi/include"
            ],
            "defines": ["STM32F407xx", "USE_HAL_DRIVER"],
            "compilerPath": "C:/Program Files (x86)/GNU Tools ARM Embedded/9 2019-q4-major/bin/arm-none-eabi-g++.exe",
            "cStandard": "c11",
            "cppStandard": "c++14",
            "intelliSenseMode": "gcc-arm"
        }
    ],
    "version": 4
}

项目配置迁移

3.1 Keil (.uvprojx) → VS Code 迁移

转换脚本示例 (Python):

# keil_to_cmake.py
import xml.etree.ElementTree as ET
import os

def convert_keil_to_cmake(uvprojx_file):
    tree = ET.parse(uvprojx_file)
    root = tree.getroot()
    
    with open('CMakeLists.txt', 'w') as f:
        f.write(f"cmake_minimum_required(VERSION 3.16)\n")
        f.write(f"project({os.path.basename(os.path.dirname(uvprojx_file))})\n\n")
        
        f.write("set(CMAKE_CXX_STANDARD 14)\n")
        f.write("set(CMAKE_C_STANDARD 11)\n\n")
        
        # 添加源文件
        f.write("# Source files from Keil project\n")
        f.write("set(SOURCES\n")
        
        # 解析Keil项目文件并添加...
        
        f.write(")\n\n")
        f.write("add_executable(${PROJECT_NAME} ${SOURCES})\n")
    
    print(f"Generated CMakeLists.txt from {uvprojx_file}")

生成的 .vscode/tasks.json:

json

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Build ARM Project",
            "type": "shell",
            "command": "arm-none-eabi-gcc",
            "args": [
                "-mcpu=cortex-m4",
                "-mthumb",
                "-specs=nano.specs",
                "-T${workspaceFolder}/STM32F407VETx_FLASH.ld",
                "${workspaceFolder}/Src/main.c",
                "-o",
                "${workspaceFolder}/build/output.elf"
            ],
            "group": "build",
            "problemMatcher": ["$gcc"]
        }
    ]
}

3.2 Eclipse (.project, .cproject) → VS Code 迁移

转换后的配置结构:

项目文件夹/
├── .vscode/
│   ├── settings.json          # 工作区设置
│   ├── tasks.json            # 构建任务
│   ├── launch.json           # 调试配置
│   └── c_cpp_properties.json # IntelliSense配置
├── CMakeLists.txt            # 替代Eclipse的build配置
├── Makefile                  # 或者使用Makefile
└── src/                      # 源代码目录

Eclipse CDT迁移后的 tasks.json:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Eclipse-like Build",
            "type": "shell",
            "command": "make",
            "args": ["-j4"],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "presentation": {
                "echo": true,
                "reveal": "always",
                "focus": false,
                "panel": "shared",
                "showReuseMessage": true,
                "clear": false
            },
            "problemMatcher": ["$gcc"]
        },
        {
            "label": "Clean Project",
            "type": "shell",
            "command": "make",
            "args": ["clean"],
            "group": "build"
        }
    ]
}

3.3 Visual Studio (.vcxproj) → VS Code 迁移

使用CMake替代方案:

# CMakeLists.txt - 替代Visual Studio项目
cmake_minimum_required(VERSION 3.20)
project(MyVSProject LANGUAGES CXX)

# 设置类似VS的配置
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# Debug配置
set(CMAKE_CXX_FLAGS_DEBUG "/MDd /Zi /Ob0 /Od /RTC1")
# Release配置
set(CMAKE_CXX_FLAGS_RELEASE "/MD /O2 /Ob2 /DNDEBUG")

# 包含目录(类似VS的附加包含目录)
include_directories(
    ${CMAKE_SOURCE_DIR}/include
    ${CMAKE_SOURCE_DIR}/thirdparty
)

# 添加可执行文件
add_executable(MyApp
    src/main.cpp
    src/utils.cpp
)

# 链接库(类似VS的附加依赖项)
target_link_libraries(MyApp
    ws2_32.lib
    user32.lib
)

调试环境统一

4.1 统一调试配置 (launch.json)

{
    "version": "0.2.0",
    "configurations": [
        // ==== ARM嵌入式调试(替代Keil)====
        {
            "name": "Cortex Debug (STM32)",
            "type": "cortex-debug",
            "request": "launch",
            "servertype": "openocd",
            "cwd": "${workspaceRoot}",
            "executable": "${workspaceFolder}/build/project.elf",
            "device": "STM32F407VG",
            "configFiles": [
                "interface/stlink-v2-1.cfg",
                "target/stm32f4x.cfg"
            ],
            "svdFile": "${workspaceFolder}/STM32F407.svd",
            "runToEntryPoint": "main"
        },
        
        // ==== Linux GDB调试(替代Eclipse)====
        {
            "name": "GDB Debug (Linux)",
            "type": "cppdbg",
            "request": "launch",
            "program": "${workspaceFolder}/build/app",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "externalConsole": false,
            "MIMode": "gdb",
            "setupCommands": [
                {
                    "description": "Enable pretty-printing for gdb",
                    "text": "-enable-pretty-printing",
                    "ignoreFailures": true
                }
            ],
            "miDebuggerPath": "/usr/bin/gdb"
        },
        
        // ==== Windows MSVC调试(替代Visual Studio)====
        {
            "name": "MSVC Debug (Windows)",
            "type": "cppvsdbg",
            "request": "launch",
            "program": "${workspaceFolder}/build/Debug/app.exe",
            "args": [],
            "stopAtEntry": false,
            "cwd": "${workspaceFolder}",
            "environment": [],
            "console": "integratedTerminal"
        }
    ]
}

统一工作流程与快捷键

5.1 统一的快捷键映射表

// .vscode/keybindings.json - 统一快捷键配置
[
    // 公共快捷键(所有IDE通用)
    {
        "key": "ctrl+shift+b",
        "command": "workbench.action.tasks.build",
        "when": "editorTextFocus"
    },
    {
        "key": "f5",
        "command": "workbench.action.debug.start",
        "when": "!inDebugMode"
    },
    {
        "key": "ctrl+f5",
        "command": "workbench.action.debug.run",
        "when": "!inDebugMode"
    },
    {
        "key": "shift+f5",
        "command": "workbench.action.debug.stop"
    },
    {
        "key": "f9",
        "command": "editor.debug.action.toggleBreakpoint"
    },
    
    // 从Keil迁移的快捷键
    {
        "key": "ctrl+f7",
        "command": "cmake.build",
        "title": "Build (Keil F7)"
    },
    
    // 从Eclipse迁移的快捷键
    {
        "key": "ctrl+shift+r",
        "command": "workbench.action.quickOpen",
        "title": "Open Resource (Eclipse Ctrl+Shift+R)"
    },
    
    // 从Visual Studio迁移的快捷键
    {
        "key": "ctrl+k+c",
        "command": "editor.action.commentLine",
        "title": "Comment (VS Ctrl+K+C)"
    },
    {
        "key": "ctrl+k+u",
        "command": "editor.action.uncommentLine",
        "title": "Uncomment (VS Ctrl+K+U)"
    }
]

5.2 统一的项目结构模板

# 创建统一的项目结构
mkdir -p my_project/{.vscode,src,include,test,docs,build}
cd my_project

# 创建统一的配置文件
cat > .vscode/settings.json << 'EOF'
{
    "[c]": {
        "editor.defaultFormatter": "ms-vscode.cpptools"
    },
    "[cpp]": {
        "editor.defaultFormatter": "ms-vscode.cpptools"
    },
    "C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools",
    "files.associations": {
        "*.inc": "c",
        "*.h": "c"
    }
}
EOF


VSCODE指南
https://www.ctuhub.top//archives/vscode-guide
作者
w-lzh
发布于
2025年12月16日
更新于
2025年12月16日
许可协议