在 VS Code 中使用 clangd

设置 VS Code clangd 检查的语言标准为 C++17

Set -std in the .yaml file and then reload window of VS Code.

CompileFlags:
    Add:
      [
        --std=c++17,
        -Wno-documentation,
        -Wno-missing-prototypes,
      ]
Diagnostics:
  ClangTidy:
    Add:
    [
        performance-*,
        bugprone-*,
        modernize-*,
        clang-analyzer-*,
        readability-identifier*,
    ]
    CheckOptions:
      readability-identifier-naming.VariableCase: camelCase

Clangd 找不到头文件

macOS 自带的 /usr/local/bin 中的 clang 不能提供查询路径。要么把绝对路径改成 PATH 中的命令,要么添加 "--query-driver=/usr/bin/clang++" 在参数中。

Windows 下,如果用的是 MSYS2 的编译器,需要添加:

"clangd.arguments": [
    "--query-driver=C:\\msys64\\mingw64\\bin\\g++.exe"
]
// ...

到配置文件中,否则跳转到的一直是 Visual Studio 的头文件。必须提供完整路径,相对路径没有效果。

有什么缺点?

对 cuda 不友好。在 cuda 文件中找不到从基类继承来的方法和属性(可能是因为用了不同的编译器?)。

对工程外的文件和头文件支持也不好,很明显,头文件不会出现在 compile_commands.json 中!

找不到 <omp.h> 文件(来自第三方库),这个警告总是无法被禁用(手动包含这个路径又会带来其他问题)。

无法显示 doxygen 文档。这一点有可能会改变,可以参考这个 github issue

多配置块在文件相互跳转的情况下无法真正工作。虽然 clangd 可以给不同的文件匹配不同的配置块,但从文件 A(打开状态)跳转到文件 B(关闭状态)时,会按照文件 A 匹配上的选项来进行分析。这导致了 CUDA 文件和 C++ 文件可能使用相同的配置。所以按照是否为 CUDA 文件提供不同的配置(编译选项不同)是不现实的。

Clangd 对于 CUDA 文件中子类从父类继承来的属性和方法的判断不对。这导致对 CRTP 的检查不能正常工作。

有哪些地方要小心?

如果是使用 VS Code 进行远程开发,一定要设置好 clangd 在开发容器里的配置(比如给出空的 clangd.arguments 数组),不然 clangd 就会使用本地上的设置!例:

{
    "clangd.path": "/usr/bin/clangd-17",
    "clangd.arguments": [],
    // ...
}

在 .clangd 配置文件中不能使用相对于工程根目录的路径。有人提交了 patch 但是现在没有回复。

VS Code 的 clangd 插件是在 build 目录下调用 clangd 分析的,所以可以用 -I../include/,前提是 build 目录就是工程根部的一个子目录。

CompileFlags:
  Add:
    - --cuda-path=/usr/local/cuda/
    - -I../include/
  Remove:
    - -forward-unknown-to-host-compiler
    - --generate-code*
    - --expt-relaxed-constexpr
    - -G

之前有时候用 -isystem 不成功是因为 .clangd 的选项是要一行一个

...
 - -isystem a/include # ×
 - -isystem           # ✔
 - a/include
 - -isystemb/include  # ✔