跳到正文

科技·工程

VSCode使用Clangd自用配置教程

thomasquan约 5 分钟
原文

这是 2025年11月19日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年11月19日
收录
2025年12月12日
更新
2026年11月15日
篇幅
约 5 分钟

版本

  1. v2当前
  2. v1

Visual Studio Code配置教程

  • 下载clangd插件
  • 打开工作目录
  • 下载LLVM-MINGW, 将bin文件夹添加到PATH
  • 重启VSCode, 随便打开一个C++文件如果在左下角看到clangd: idle就是成功了
  • 在工作目录创建build.cpp并写入
C++
#include <bits/stdc++.h>
#include <windows.h>

using namespace std;

char command[1010];
int ret;
double s, e;
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);

void SetFont(const wchar_t *s) {
  CONSOLE_FONT_INFOEX fontInfo;
  fontInfo.cbSize = sizeof(fontInfo);
  fontInfo.nFont = 1;
  fontInfo.dwFontSize.X = 0;
  fontInfo.dwFontSize.Y = 30;
  fontInfo.FontFamily = FF_DONTCARE;
  fontInfo.FontWeight = FW_NORMAL;
  wcscpy(fontInfo.FaceName, s);
  SetCurrentConsoleFontEx(hOut, 0, &fontInfo);
}

int main(int n, char *args[]) {
  SetFont(L"Consolas");
  if (n <= 1) {
    cout << "Build failed. \n";
    return 0;
  }
  sprintf(command, "clang++ %s.cpp -o %s ", args[1], args[1]);
  for (int i = 2; i < n; i++) {
    strcat(command, args[i]);
    strcat(command, " ");
  }
  cout << "Compiling. . . \n";
  ret = system(command);
  if (ret)
    cout << "Compilation failed with return value " << ret << endl;
  else {
    cout << "Compilation completed. \n";
    cout << "Running. . . \n";
    s = 1.0 * clock() / CLOCKS_PER_SEC;
    sprintf(command, "%s", args[1]);
    ret = system(command);
    e = 1.0 * clock() / CLOCKS_PER_SEC;
    cout << "\nTask exited with return value " << ret << " in "
         << setprecision(3) << fixed << e - s << " seconds. \n";
  }
  system("pause");
  return 0;
}
  • 在命令行里将build.cpp编译成build.exe
  • build相当于是一个编译运行文件, 比如如果你在使用A.cpp, 你可以运行build A
  • 在.vscode\tasks.json写入
JSON
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "shell",
            "command": "start",
            "args": [
                "cmd",
                "/c",
                "build",
                "${fileDirname}\\${fileBasenameNoExtension}"
            ],
            "presentation": {
                "reveal": "silent"
            },
            "options": {
                "cwd": "${workspaceFolder}",
                "shell": {
                    "executable": "cmd",
                    "args": [
                        "/c"
                    ]
                }
            },
            "problemMatcher": []
        }
    ]
}
  • 按下Ctrl+K, Ctrl+S打开键盘设置, 左上角打开JSON文件, 写入
JSON
[
    {
        "key": "F5",
        "command": "workbench.action.tasks.runTask",
        "args": {
            "task": "build"
        }
    },
]

这样你就可以按F5运行代码了.

如果你想要格式化代码可以按Alt+Shift+F或者你可以在设置里面搜索Format On …

  • Format On Save: 每次保存时格式化代码
  • Format On Paste: 每次粘贴代码时格式化代码
  • Format On Type: 一边打代码一边格式化