CICD中clang-tidy静态语义检查

2023-05-16

教程;
https://hokein.github.io/clang-tools-tutorial/
要用clang-tidy首先要在电脑上安装clang-tools
Linux Ubuntu系统

sudo apt install clang-tools

装好后就可以看到clang-tidy以及其它相关工具了。

clang-tidy 官方文档
接下来我们要使用clang-tidy-8 --help,注意最后面

Configuration files:
  clang-tidy attempts to read configuration for each source file from a
  .clang-tidy file located in the closest parent directory of the source
  file. If any configuration options have a corresponding command-line
  option, command-line option takes precedence. The effective
  configuration can be inspected using -dump-config:

    $ clang-tidy -dump-config
    ---
    Checks:          '-*,some-check'
    WarningsAsErrors: ''
    HeaderFilterRegex: ''
    FormatStyle:     none
    User:            user
    CheckOptions:
      - key:             some-check.SomeOption
        value:           'some value'
    ...

就是说你可以通过建立一个文件.clang-tidy来减少命令行中-checks= option的命令。

在你需要检查的文件夹下建立文件.clang-tidy
在.clang-tidy中

{
Checks: "-*,bugprone-*,cert-*,clang-analyzer-*,cppcoreguidelines-avoid-goto,cppcoreguidelines-c-copy-assignment-signature,cppcoreguidelines-interfaces-global-init,cppcoreguidelines-narrowing-conversions,cppcoreguidelines-no-malloc,cppcoreguidelines-pro-bounds-constant-array-index,cppcoreguidelines-pro-type-const-cast,cppcoreguidelines-pro-type-cstyle-cast,cppcoreguidelines-pro-type-member-init,cppcoreguidelines-pro-type-reinterpret-cast,cppcoreguidelines-pro-type-static-cast-downcast,cppcoreguidelines-pro-type-union-access,cppcoreguidelines-slicing,cppcoreguidelines-special-member-functions,google-build-*,google-default-arguments,google-explicit-constructor,google-global-names-in-headers,google-objc-*,google-readability-casting,google-readability-function-size,google-readability-namespace-comments,google-readability-todo,google-runtime-operator,hicpp-avoid-goto,hicpp-deprecated-headers,hicpp-exception-baseclass,hicpp-explicit-conversions,hicpp-function-size,hicpp-invalid-access-moved,hicpp-member-init,hicpp-move-const-arg,hicpp-multiway-paths-covered,hicpp-named-parameter,hicpp-new-delete-operators,hicpp-no-assembler,hicpp-no-malloc,hicpp-noexcept-move,hicpp-special-member-functions,hicpp-static-assert,hicpp-undelegated-constructor,hicpp-use-*,misc-*,modernize-*,-modernize-use-trailing-return-type,performance-*,readability-avoid-const-params-in-decls,readability-container-size-empty,readability-delete-null-pointer,readability-deleted-default,readability-else-after-return,readability-function-size,readability-identifier-naming,readability-inconsistent-declaration-parameter-name,readability-misleading-indentation,readability-misplaced-array-index,readability-named-parameter,readability-non-const-parameter,readability-redundant-*,readability-simplify-*,readability-static-*,readability-string-compare,readability-uniqueptr-delete-release,readability-rary-objects"
}

这些就是检测规则
然后执行:

clang-tidy-8 -p ${PWD} -dump-config

然后运行clang-tidy

clant-tidy-8 --quite -p ./ src.cpp

这里注意-p 参数,在help里是这样说的

-p <build-path> is used to read a compile command database.

	For example, it can be a CMake build directory in which a file named
	compile_commands.json exists (use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
	CMake option to get this output). When no build path is specified,
	a search for compile_commands.json will be attempted through all
	parent paths of the first input file . See:
	http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html for an
	example of setting up Clang Tooling on a source tree.

很多童鞋遇到一个问题:

rror while trying to load a compilation database:
Could not auto-detect compilation database from directory "./"
No compilation database found in /builds/crystal/crystal-media/ or any parent directory

就是因为上述原因引起的,所以我们通过-p来指定compile_commands.json的位置,官方文档说明

z这里还有一个问题,如果你使用的是qmake,那么如何使用qmake来clang-tidy呢?
问题解决入口
howtouseclangtidyinQt

具体检查规则:
1、readability-identifier-naming (规则2.1.1)

这条规则是用来检查名命名规则的。在这条总的规则之下,还有关于具体要检查项的key和value。比如:

  • key: readability-identifier-naming.ClassCase

    value: CamelCase

这里ClassCase说明检查的是类的命名,CamelCase说明要求的风格是大驼峰命名法。方舟里涉及到命名规则,目前有CamelCase(大驼峰命名法)、camelBack(小驼峰命名法)和lower_case(小写命名法)。涉及到的检查项主要有ClassCase(类)、StructCase(结构体)、TypedefCase(Typedef)、EnumCase(枚举)、EnumConstantCase(枚举常量)、UnionCase(联合)、NamespaceCase(命名空间)、FunctionCase(函数)、VariableCase(变量)、ConstantCase(常量)。

2、readability-function-size

这条规则是用来检查函数的大小的。总规则之下,也包含了两条具体的检查项。

  • key: readability-function-size.StatementThreshold

    value: 50

检查函数内的语句不超过50条。(建议8.1.1)

  • key: readability-function-size.ParameterThreshold

    value: 5

检查函数的参数不超过5个。(建议8.3.3)

3、readability-braces-around-statements

语句必须在大括号之内。这里主要是针对条件判断之后进行执行的语句,比如if-else,哪怕是只有一条语句,也应该在括号之内。(规则3.6.1,规则3.7.1)

4、readability-magic-numbers

魔鬼数字检查。(建议9.1.3)

5、misc-unused-parameters

未使用函数参数检查。

6、modernize-use-nullptr

检查使用nullptr,而不是NULL或0。(规则10.1.3)

7、modernize-replace-auto-ptr

检查禁止使用auto_ptr。(规则9.5.2)

8、modernize-use-noexcept

检查不使用异常机制。(规则11.4.1)

9、modernize-use-override

检查重写虚函数时使用override关键字。(规则10.1.1)

10、performance-move-const-arg

检查禁止使用std::move操作const对象。(规则10.1.4)

11、cppcoreguidelines-pro-type-cstyle-cast

不使用C风格转换检查。(规则9.3.1)

12、cppcoreguidelines-pro-type-reinterpret-cast

不使用reinterpret_cast 检查。(建议9.3.2)

13、cppcoreguidelines-pro-type-const-cast

不使用const_cast检查。(建议9.3.3) 作者:小乖他爹-知乎 https://www.bilibili.com/read/cv5153605 出处:bilibili
具体脚本如下:

#/bin/bash
# check code quality with clang-tidy
#crystalmedia

VERSION=debug
cd ./${CI_PROJECT_NAME}_${VERSION}
DIR_BUILD=${PWD}
echo PWD:${PWD}
ls

echo "${PROMPT}================= Check with Clang-tidy ======================"
chk_report="${DIR_BUILD}/clang-tidy-check.txt"
rm -f $chk_report
touch $chk_report
echo "${PROMPT}Report filename: $chk_report"
echo "${PROMPT}Current directory: ${PWD}"
echo "${PROMPT}Clang-tidy configuration:"
clang-tidy-8 -p ${DIR_BUILD} -dump-config

fifo="/tmp/$$.fifo" # a file for pipe
mkfifo $fifo # a pipe as the process queue
exec 6<>$fifo # attach fd #6 to the pipe
thread_num=8 # max processes number
count=0;

while [[ $count -lt $thread_num ]]; do
  echo >&6
  #let count=count+1
  count=$((count + 1 ))
done

fail_flag_file="./quality-failed.txt"
file_list=$(find -name '*.cpp' )
#file_list=$(find \( -path './ptz' -o -path './vcnkit' \) -prune -o -name '*.cpp' -print)
echo -e ${file_list}
for src_file in $file_list; do
  read -u6
  {
      if [[ $(basename $src_file) != moc_* && $(basename $src_file) != test_* && $(basename $src_file) != qrc_* && $(basename $src_file) != AES* ]]; then
          time_start=$(date +%s)
          echo "${PROMPT}Analyzing: $src_file"
          eval "clang-tidy-8 --quiet -p ./ $src_file >>$chk_report"

          [ $? -ne 0 ] && echo "FAIL" > $fail_flag_file

          time_end=$(date +%s)
          duration=$[${time_end}-${time_start}]
          if [[ ${print_job_duration} == "on" ]]; then
            echo ${PROMPT}"Task duration time: ${duration}"
          fi
          if [[ ${duration} -gt ${task_duration_limit} ]]; then
            echo ${PROMPT}"Warning: This task takes time more than ${task_duration_limit} seconds."
          fi
      fi
      # produce a cook
      echo >&6
  }&
done
wait
exec 6>&-
rm $fifo

if  [ -f $fail_flag_file ];then
    CHECK_PASS=NO
else
    CHECK_PASS=YES
fi


# check report
[ $(cat $chk_report | wc -l) -gt 0 ] && CHECK_PASS=NO

echo "${PROMPT}=================== Clang-tidy Report ========================"
cat $chk_report
echo "${PROMPT}=============================================================="

#cp $chk_report ${DIR_BUILD}/*check.txt ${DIR_BUILD}/
#cp ${DIR_BUILD}/compile_commands.json ../compile_commands.json

# exit
if [ "#$CHECK_PASS" = "#NO" ]; then
    exit 1;
    echo ${PROMPT}Cod Quality check failed.
fi
exit 0

clang-tidy静态语义检查,安装、使用、检查项注解

我们先来看一下clang与LLVM之间的区别与联系
LLVM与Clang的概述及关系

深入浅出让你理解什么是LLVM

在这里插入图片描述
还有一个clang-format
.clang-format

# Installation:
#   sudo apt install clang-format-8
# Reference:
#       http://clang.llvm.org/docs/ClangFormatStyleOptions.html
#
# 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.

BasedOnStyle: LLVM

Cpp11BracedListStyle: true

Language: Cpp

# Cpp03, Cpp11, Auto
Standard: Cpp14
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

CICD中clang-tidy静态语义检查 的相关文章

随机推荐

  • 华东师范大学计算机学硕2023考研经验贴

    文章目录 1 个人经历1 1 一战1 2 二战1 3 心态 2 初试2 1 政治2 2 英语2 3 数学2 4 408 3 复试3 1 机试A 数字猜想B 特殊质数C 最小字符串D 数字排序E 整数分解 3 2 英语面试3 3 综合面试 1
  • Go后端部署服务器

    go后端部署服务器方式一 xff1a xff08 最简单 xff09 和暑假做重点场所项目部署一样 xff0c 简单 xff0c 无脑 xff0c 手动 xff0c 麻烦 span class token number 1 span spa
  • 数据分析实用python程序

    文章目录 1 pdf转txt2 判断txt文件是否为空3 获取txt文件每一行4 获取文件夹所有文件名5 读写xlsx表格6 遍历txt每个字符7 字符串中字符替换 1 pdf转txt span class token comment de
  • 51单片机之数码管

    1 静态数码管原理图 LED数码管根据LED的不同接法分为两类 xff1a 共阴和共阳 为了显示数字或字符 xff0c 必须对数字或字符进行编码 七段数码管加上一个小数点 xff0c 共计8段 因此为LED显示器提供的编码正好是一个字节 共
  • 银行排队模拟(队列)

    银行排队模拟程序 队列类Queue ifndef span class token constant QUEUE H span define span class token constant QUEUE H span struct Rec
  • C/C++中struct和class的区别

    目录 struct class struct和class的区别 struct struct是描述一个数据结构的集合 xff0c 像一周有七天 xff0c 你可以把一周看成是一个结构体 xff0c 然后在结构体里面定义一个数组来存放这个七天
  • java枚举(enum)使用详解

    文章目录 前言一 枚举类型定义二 访问成员三 遍历四 在switch xff08 xff09 中使用枚举五 方法1 内置方法1 1 ordinal 用于返回成员的索引1 2 compareTo 用于比较枚举类型中两个成员的索引值1 3 va
  • 分析url从输入到展过程中的页面优化、performance

    浏览器会开启一个线程处理URL请求 url从输入到展示页面的过程 1 输入网址 2 DNS解析 3 建立tcp连接 xff08 请求队列queuing 请求等待stalled 4 客户端发送HTPP请求 5 服务器处理请求 6 服务器响应请
  • 双重锁单例模式

    不忘初心 xff0c 思考梦开始的地方 普通的懒汉式和饿汉式都不用管 简单实现一下线程安全的方式 span class token keyword public span span class token keyword class spa
  • VScode神仙插件,程序员必备

    前言 Visual Studio Code VS Code 是微软2015年推出的一个轻量但功能强大的源代码编辑器 xff0c 基于 Electron 开发 xff0c 支持 Windows Linux 和 macOS 操作系统 它内置了对
  • 【Java】使用Java实现爬虫

    文章目录 使用Java实现爬虫一 HttpClient实现模拟HTTP访问1 1 HttpClient1 2 引入依赖1 3 创建简单的请求操作1 3 1 创建实例1 3 2 Jsoup应用 1 4 爬取过程中可能出现的问题1 4 1 JS
  • STM32 HAL库+ESP8266+华为云物联网平台

    文章内容 xff1a STM32 HAL库通过串口发送AT指令完成与ESP8266的控制实现接入华为云物联网平台 xff0c 并完成基本通信与控制 xff0c 包括设备属性上报和命令下发解析与响应 文末获取 STM32 HAL库 43 ES
  • MySQL事务篇

    文章目录 说明 xff1a 事务篇一 事务隔离级别是怎么实现的 xff1f 二 MySQL 可重复读隔离级别 xff0c 完全解决幻读了吗 xff1f 说明 xff1a 此类文章是为小林coding的图解MySQL xff0c 所简写 xf
  • Android studio TCP网络调试助手应用开发(支持TCP Server与Client切换)

    在前几篇的文章中带大家完成了基于TCP的物联网安卓应用开发 xff0c 教程内容是创建了一个TCP客户端并连接服务器完成数据通信的过程 xff0c 后不久又发布了一个ESP8266创建TCP 服务器与安卓的客户端进行通信的一个文章 xff0
  • 【FreeRTOS】中断管理

    在介绍本文之前 xff0c 向大家推荐个非常容易入门的人工智能学习网站 xff0c 建议点击收藏 目录 xff1a 1 前言2 内核提供两套API2 1 优点2 2 缺点2 3 常用API函数列表2 4 pxHigherPriorityTa
  • 【嵌入式基础】内存(Cache,RAM,ROM,Flash)

    1 前言 最近在看赛普拉斯的一款芯片CYW8019规格书 xff0c 里面有好几个内存的关键字 xff08 如下图的右上方 xff09 xff0c 本文将聊它们的含义和作用 2 Cache Cache是集成在CPU内部的极高速缓存 一般来讲
  • 使用Promise解决多个请求数据并发问题

    首先引用一下阮一峰大佬的一段话 xff1a Promise xff0c 简单说就是一个容器 xff0c 里面保存着某个未来才会结束的事件 xff08 通常是一个异步操作 xff09 的结果 从语法上说 xff0c Promise是一个对象
  • 1. KVM虚拟化学习

    1 什么是虚拟化 虚拟化 xff0c 通过模拟计算机的硬件 xff0c 来实现同一台计算机上运行多个不同的操作系统的既技术 2 为什么要使用虚拟化 为了充分利于资源 xff0c 软件运行环境的隔离 xff0c 只要有虚拟化才能实现 虚拟化提
  • 二次再散列法

    散列表 设所有可能出现的关键字集合记为U 简称全集 实际发生 即实际存储 的关键字集合记为K xff08 K 比 U 小得多 xff09 散列方法是使用函数h将U映射到表T 0 m 1 的下标上 xff08 m 61 O U xff09 这
  • CICD中clang-tidy静态语义检查

    教程 xff1b https hokein github io clang tools tutorial 要用clang tidy首先要在电脑上安装clang tools Linux Ubuntu系统 span class token fu