Skip to content
Go back

vscode 中使用 clang+clangd+lldb

在 vscode 中使用 clang+clangd+lldb

安装


# Ubuntu
sudo apt install clangd clang clang-format
# sudo apt install lldb

vscode 插件中需安装 clangd, CMake Tools, CodeLLDB

  • 更新: llvm 官方推出了 lldb-dap ,基于 vscode dap 协议开发。与 CodeLLDB 区别见 CodeLLDB vs lldb-dap,两者配置方法类似。

自动补全

相比与微软官方的 C/C++ 插件,个人更喜欢用 clangd 插件,当然 C/C++ Advanced Lint 等插件也不错。需要注意的是,clangd 插件中还带有代码格式化功能,开启此插件会替换掉 C/C++插件的代码格式化。

此外启用 clangd 之后,头文件的管理也不是在 .vscode/c_cpp_properties.json 中了,需要 compile_commands.json 文件,CMake 配置如下。

# 生成 compile_commands.json
set ( CMAKE_EXPORT_COMPILE_COMMANDS ON )

调试


CMake Tools 插件中选择使用 Clang-12 工具链,截止本文撰写日期,CMake Tools 还不能正常启动 lldb 调试,只能用 gdb,所以还是使用 CodeLLDB 插件 + launch.json 的方式调试。

CodeLLDB 插件中内嵌了一个 LLDB,不需要另外安装,用法也很简单,如下。

{
    "name": "Launch",
    "type": "lldb",
    "request": "launch",
    "program": "${workspaceFolder}/<my program>",
    "args": ["-arg1", "-arg2"],
    "initCommands": [
        "command script import xxxxx.py"
    ]
}

进阶调试


要加入其他插件也很方便。比如说 CodeLLDB 附带的 显示图片脚本 ,以及 lldbinit

这里有一点需要注意,目前 CodeLLDB 内置的 python 是 3.9 版本,而 Ubuntu 20.4 默认是 3.8 版本 ( 截至 2021.12 ) 。在装包的时候需要注意。

python3.9 -m pip install --user matplotlib --upgrade --ignore-installed

这里我参考了几个项目,修改了 CodeLLDB 附带的 显示图片脚本 ,使其支持 cv:: Mat,如下图

lldb 显示 cv::mat
lldb 显示 cv::mat

脚本链接: debugvis.py

使用说明:

  1. ~/.lldbinit 中加入 command script import {your location}/debugvis.py
  2. 假设要查看的 cv:: Mat 图片为 image
  3. 方法 1: vscode 中创建 conditional breakpoint,输入 /py debugvis.plot_cvimage ( $image )
  4. 方法 2: debug console 中输入 imshow image

参考: https://github.com/vadimcn/vscode-lldb/wiki/Data-visualization https://github.com/longcw/LLDB-Opencv-Data-Formatter https://github.com/houqi/CvMatForLLDB


Share this post on: