clang-tidy 使用指南

clang-tidy 是一个用于 C++ 代码的静态分析工具,可以帮助你发现代码中的潜在问题和改进点。

  1. 安装 clang-tidy cmake
    首先,你需要确保已经安装了 clang-tidy, cmake。你可以使用包管理器来安装它,例如在 Ubuntu 上:

sudo apt-get install clang-tidy cmake
2. 创建项目并生成编译数据库
clang-tidy 需要一个编译数据库来了解如何编译你的代码。编译数据库通常是一个名为 compile_commands.json 的文件。你可以使用 CMake 来生成这个文件。

创建 CMakeLists.txt 文件:

在你的项目根目录下创建一个 CMakeLists.txt 文件,内容如下:

cmake_minimum_required(VERSION 3.5)
project(TestProject)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)

add_executable(test test.cpp)

生成编译数据库:

在终端中运行以下命令:

mkdir build
cd build
cmake ..

这将在 build 目录中生成一个 compile_commands.json 文件。

  1. 运行 clang-tidy
    现在你可以使用生成的编译数据库运行 clang-tidy。例如,要对 test.cpp 文件运行所有可用的检查规则,可以使用以下命令:
clang-tidy-20 ../test.cpp -checks='*' -p build
  1. 示例代码
    以下是一个示例代码文件 test.cpp:
#include <vector>

class X {
public:
    void addElement() {
        m_.push_back(1);
    }

private:
    std::vector<int> m_;
};

void test() {
  int x;
  x = 1; // warn
}

int main() {
    X x;
    x.addElement();
    return 0;
}

在这个示例中,clang-tidy 会对 test.cpp 文件进行分析,并报告任何潜在的问题。例如,它可能会警告 test 函数中的未使用变量 x。

  1. 常见问题
    找不到编译数据库:如果 clang-tidy 报告找不到编译数据库,请确保你在运行 clang-tidy 时使用了 -p 选项,并指定了包含 compile_commands.json 文件的目录。

指定检查规则:你可以使用 -checks 选项来指定要运行的检查规则。例如,-checks=‘-*,clang-analyzer-deadcode.DeadStores’ 只运行 clang-analyzer-deadcode.DeadStores 检查

clang-tidy checkers:
https://clang.llvm.org/docs/analyzer/checkers.html#deadcode-deadstores-c

对于实际的大型工程使用
.clang-format 配置检查规则,
.clang-format-ignore 忽略的检查项,

对于具体文件忽略检查

Clang-format understands also special comments that switch formatting in a delimited range. The code between a comment // clang-format off or /* clang-format off / up to a comment // clang-format on or / clang-format on */ will not be formatted. The comments themselves will be formatted (aligned) normally. Also, a colon (😃 and additional text may follow // clang-format off or // clang-format on to explain why clang-format is turned off or back on.

    int formatted_code;

    // clang-format off

        void    unformatted_code;

    // clang-format on

    void formatted_code_again;

You want to disable formatting of a single source file? // clang-format off in that file.
You want to disable formatting for third party code? .clang-format with DisableFormat: true in that directory resp. your directory for all 3rd party code

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值