跳到主要内容

Clangd 使用指南

· 阅读需 3 分钟
Hanmi255
游戏开发 & AI研究者

如何在 VSCode 或者 Cursor 中使用 Clangd 插件?

为什么使用 Clangd?

我之前在 VSCode 中制作 C++ 项目,在我想使用 Cursor 继续制作 C++ 项目时, 发现 Cursor 不再支持 VSCode 中的 C++ 插件ms-vscode.cpptools, 而是改成了 anysphere.cpptools,并且必须额外安装 clangd 插件 llvm-vs-code-extensions.vscode-clangd

一些爱恨情仇(233333...)

可以查看以下内容补充了解情况

Cursor Discussion

[SOLVED] C/C++ Extension

Github Issue

Has the VSCode C/C++ Extension been blocked?

Medium

Microsoft Quietly Blocked Cursor from Using Its VSCode Extension — Here’s the Line of Code That Did It

产生的问题

这导致 .vscode/c_cpp_properties.json 文件中的内容无法被识别(例如一些 include_path),产生下面的虚假错误:

危险

'spdlog/spdlog.h' file not found clang(pp_file_not_found)

而实际上可以正确编译运行。

为了解决这个问题,我决定使用 Clangd 插件,生成 compile_commands.json 文件,

如何配置 Clangd?

安装 Clangd 本体

Clangd Release 中下载,选择合适的版本和对应系统的 Clangd 压缩包解压。

配置环境变量

添加 CLANGD_ROOT 环境变量,值为 your_clangd_path,例如:'D:\Clangd\clangd_20.1.8'。

在 PATH 中添加 %CLANGD_ROOT%\bin

安装 Clangd 插件

在 VSCode 或 Cursor 中安装 llvm-vs-code-extensions.vscode-clangd 插件。

并按照下图设置 Clangd 的路径: Clangd 插件设置

配置 settings.json

使用 Ctrl + Shift + PF1 打开命令面板,输入 Preferences: Open Settings (JSON),然后添加以下内容:

"clangd.arguments": [
"--background-index",
"--compile-commands-dir=${workspaceFolder}/build", // compile_commands.json 的路径
"-j=12",
"--all-scopes-completion",
"--completion-style=detailed",
"--header-insertion=iwyu",
"--pch-storage=memory",
"--cross-file-rename",
"--enable-config",
"--fallback-style=WebKit",
"--pretty",
"--clang-tidy",
],
"C_Cpp.intelliSenseEngine": "disabled", // 禁用 C/C++ 插件的IntelliSense

CMake 配置

配置 CMakeLists.txt

额外添加以下内容,其余正常配置:

set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

选择 GCC 或 Clang 的编译器

注意

千万不要选择 MSVC 编译器,否则无法生成 compile_commands.json 文件。

使用 Clangd 的优势?

  1. IntelliSense 比 C/C++ 插件更智能
  2. 对于未使用的头文件,会提示删除
  3. 跳转更灵活, C/C++ 插件甚至会卡顿