VSCode + WSL + clangd +CMake + CMake Tools搭建C++开发环境

1. 前言

开始安装前先了解以下概念:

简而言之 clang + llvm == gcc,它们是 C++ 代码编译器。而 clangd 是一个 C++ 静态语法分析工具,提供代码提示,自动补全,代码跳转等功能。

2. 安装 WSL 环境

首选需要在 Win10 上安装 WSL Linux 环境,这是进行开发的基础。

离线安装WSL & 导出与导入WSL(60)

3. 环境搭建

3.1. 所需插件

CMake

简介:CMake 语法补全,语法高亮。

CMake Tools

简介:CMake 工程构建工具。

CMake Language Support

简介:CMake 语法支持。

clangd

简介:C/C++ 语法分析插件。

Clang-Format

简介:代码格式化工具。

CodeLLDB

简介:A native debugger powered by LLDB. Debug C++ , Rust and other compiled languages.

GN

简介:在 VSCode 中编辑 GN 文件,GN 语法高亮显示。

3.2. 配置 clangd 环境

VSCode 编写 C++ 代码若想用 clangd 实现代码提示,自动补全,代码跳转等功能的完整路径为:VSCode 编辑器 + VSCode clang 插件 + clangd language server。工作原理:"VSCode clang 插件" 工作在 VSCode 编辑器端,它把语法分析请求发送给"clangd language server",然后 "clangd language server" 把分析结果反馈给 VSCode 编辑器,这样 VSCode 编辑器就能实现代码提示,自动补全,代码跳转等功能。

1、卸载 VSCode 的C/C++插件。必须步骤,它和 VSCode 的 clangd 插件冲突。

2、安装 VSCode clangd插件,安装完此插件,首次打开后,会自动安装 "clangd language server"。但是 "clangd language server" 下载比较慢,可以自己去 github 上下载 release 包,手动安装。

手动安装 "clangd language server":

  1. 打开clangd language server github 网站。

  2. 下载 release 包:

  1. 解压到 WSL 的 /usr/local 目录中:
 unzip clangd-linux-14.0.3.zip -d /usr/local/
  1. 把 "clangd language server" 添加到 WSL 的 PATH 环境变量中,必须操作,否则无法识别。

vim ~/.bashrc,在文件末尾添加如下内容:

# clangd
export PATH="/usr/local/clangd_14.0.3/bin:$PATH"

3、在 VSCode 中编写 C++ 代码,并生成 compile_commands.json 文件。关于生成 compile_commands.json 的方法参看官方文档:Getting started

4、打开任意一个 cpp 文件,VSCode clangd 插件就会根据 compile_commands.json 文件的描述建立索引,建立好的索引放在当前工程的 .cache 目录下。若想重新建立索引,则删除 .cache 目录,然后打开任意一个 cpp 文件,重新触发索引建立过程。

5、若是 VSCode + mingw 环境搭建,则需要告诉 clangd 插件编译器的位置,否则会提示找不到头文件。

打开 clangd 插件设置,添加如下配置:

也可直接在 settings.json 中添加如下配置:

"clangd.arguments": [
  "--query-driver=C:\\mingw64\\bin\\*.exe"
]

3.3. 安装调试插件

安装 "CodeLLDB" 插件,"CMake" 插件和 "CMake Tools" 插件。

3.4. 调试代码

1、用 "CMake: Build" 指令编译。

2、在 VSCode 菜单栏依次点击 "运行" > "添加配置" > "LLDB" > 会生成 launch.json 文件,VSCode 根据 launch.json 文件中的配置就能运行代码了。

launch.json 文件内容:

{
    // 使用 IntelliSense 了解相关属性。
    // 悬停以查看现有属性的描述。
    // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "lldb",
            "request": "launch",
            "name": "Debug",
            "program": "${workspaceFolder}/<executable file>",
            "args": [],
            "cwd": "${workspaceFolder}"
        }
    ]
}

参数说明:

  • program:指定 "CMake: Build" 生成的二进制的路径,一般在 build 目录下;
  • args:程序启动参数。

3、打断点,在 VSCode 菜单栏依次点击 "运行" > "启动调试/以非调试模式运行" 启动运行与调试。

4. clangd 选项

[18:38:26  /opt/clangd_14.0.3/bin]$ clangd --help-list
OVERVIEW: clangd is a language server that provides IDE-like features to editors.

It should be used via an editor plugin rather than invoked directly. For more information, see:
        https://clangd.llvm.org/
        https://microsoft.github.io/language-server-protocol/

clangd accepts flags on the commandline, and in the CLANGD_FLAGS environment variable.

USAGE: clangd [options]

OPTIONS:
  --all-scopes-completion         - If set to true, code completion will include index symbols that are not defined in the scopes (e.g. namespaces) visible from the code completion point. Such completions can insert scope qualifiers
  --background-index              - Index project code in the background and persist index on disk.
  --check[=<string>]                - Parse one file in isolation instead of acting as a language server. Useful to investigate/reproduce crashes or configuration problems. With --check=<filename>, attempts to parse a particular file.
  --check-lines[=<string>]          - If specified, limits the range of tokens in -check file on which various features are tested. Example --check-lines=3-7 restricts testing to lines 3 to 7 (inclusive) or --check-lines=5 to restrict to one line. Default is testing entire file.
  --clang-tidy                    - Enable clang-tidy diagnostics
  --compile-commands-dir=<string> - Specify a path to look for compile_commands.json. If path is invalid, clangd will look in the current directory and parent paths of each source file
  --completion-style=<value>      - Granularity of code completion suggestions
    =detailed                     -   One completion item for each semantically distinct completion, with full type information
    =bundled                      -   Similar completion items (e.g. function overloads) are combined. Type information shown where possible
  --enable-config                 - Read user and project configuration from YAML files.
                                    Project config is from a .clangd file in the project directory.
                                    User config is from clangd/config.yaml in the following directories:
                                        Windows: %USERPROFILE%\AppData\Local
                                        Mac OS: ~/Library/Preferences/
                                        Others: $XDG_CONFIG_HOME, usually ~/.config
                                    Configuration is documented at https://clangd.llvm.org/config.html
  --fallback-style=<string>       - clang-format style to apply by default when no .clang-format file is found
  --function-arg-placeholders     - When disabled, completions contain only parentheses for function calls. When enabled, completions also contain placeholders for method parameters
  --header-insertion=<value>      - Add #include directives when accepting code completions
    =iwyu                         -   Include what you use. Insert the owning header for top-level symbols, unless the header is already directly included or the symbol is forward-declared
    =never                        -   Never insert #include directives as part of code completion
  --header-insertion-decorators   - Prepend a circular dot or space before the completion label, depending on whether an include line will be inserted or not
  --help                          - Display available options (--help-hidden for more)
  -j=<uint>                       - Number of async workers used by clangd. Background index also uses this many workers.
  --limit-references=<int>        - Limit the number of references returned by clangd. 0 means no limit (default=1000)
  --limit-results=<int>           - Limit the number of results returned by clangd. 0 means no limit (default=100)
  --log=<value>                   - Verbosity of log messages written to stderr
    =error                        -   Error messages only
    =info                         -   High level execution tracing
    =verbose                      -   Low level details
  --malloc-trim                   - Release memory periodically via malloc_trim(3).
  --offset-encoding=<value>       - Force the offsetEncoding used for character positions. This bypasses negotiation via client capabilities
    =utf-8                        -   Offsets are in UTF-8 bytes
    =utf-16                       -   Offsets are in UTF-16 code units
    =utf-32                       -   Offsets are in unicode codepoints
  --path-mappings=<string>        - Translates between client paths (as seen by a remote editor) and server paths (where clangd sees files on disk). Comma separated list of '<client_path>=<server_path>' pairs, the first entry matching a given path is used. e.g. /home/project/incl=/opt/include,/home/project=/workarea/project
  --pch-storage=<value>           - Storing PCHs in memory increases memory usages, but may improve performance
    =disk                         -   store PCHs on disk
    =memory                       -   store PCHs in memory
  --pretty                        - Pretty-print JSON output
  --project-root=<string>         - Path to the project root. Requires remote-index-address to be set.
  --query-driver=<string>         - Comma separated list of globs for white-listing gcc-compatible drivers that are safe to execute. Drivers matching any of these globs will be used to extract system includes. e.g. /usr/bin/**/clang-*,/path/to/repo/**/g++-*
  --remote-index-address=<string> - Address of the remote index server
  --version                       - Display the version of this program

5. 自动格式化 C++ 代码

clang-format 工具可以根据一定的规则(通过 .clang-format 文件指定)自动格式化 C++ 代码。只要项目制定一套统一的规则下来,那么用这个工具格式化后每个人写的代码的风格就一样,而不再有调格式的烦恼。

参看《Win10 + VSCode + clang format格式化C++代码》。

6. 常见问题汇总

● 部署相同的两套代码方便开发,其中有一套 clangd 不扫描建立缓存?

解决方案:这是缓存影响的。

1、备份 .vscode-server/data/Machine 目录。

2、删除 .vscode-server/data 目录。

3、重新打开 vscode 工程,这时候 clangd 就会开始建立缓存了。

4、等 clangd 开始建立缓存后,再还原 .vscode-server/data/Machine 目录。

5、如果还是不行的话,就把 .vscode-server/data 目录删掉,并把用户级配置文件,remote 配置文件全部清空。在重新打开,即可开始建立索引。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值