chapter09 - program analysis tools
说明
这一章节是作者将一些分析工具以函数或内置支持的形式自动化地加入到了 CMake 构建工程的过程中了。
格式化
clang-format
静态检查
- clang-tidy
- cpplint(按照 Google Coding Style 检查)
- cppcheck
- include-what-you-use
- link what you use(CMake 内置)
静态检查受到 CMake 的直接支持:
All we need to do is set an appropriate target property to a semicolon-separated list containing the path to the checker’s executable, followed by any command-line options that should be forwarded to the checker.
<LANG>_CLANG_TIDY
<LANG>_CPPCHECK
<LANG>_CPPLINT
<LANG>_INCLUDE_WHAT_YOU_USE
LINK_WHAT_YOU_USE
比如:
set(CMAKE_CXX_CLANG_TIDY /usr/bin/clang-tidy-3.9;-checks=*)
以 clang-tidy 为例,除了设置全局的 CMAKE_<LANG>_CLANG_TIDY
之外,还能对 target 设置 <LANG>_CLANG_TIDY
属性:
function(AddClangTidy target)
find_program(CLANG-TIDY_PATH clang-tidy REQUIRED)
set_target_properties(${target}
PROPERTIES CXX_CLANG_TIDY
"${CLANG-TIDY_PATH};-checks=*;--warnings-as-errors=*"
)
endfunction()
这样在构建的时候就会自动检查,不过这也会使得构建变得很慢。
用 valgrind 动态检查
valgrind 介绍
使用方式:
valgrind [valgrind-options] tested-binary [binary-options]
使用 memcheck 直接省略 options 即可,因为它是默认的工具,当然也可以显式指定:
valgrind --tool=memcheck tested-binary
实际上它的功能还有很多:
Some of the tools are as follows:
- Memcheck – detects memory-management problems
- Cachegrind – profiles CPU caches, and pinpoints cache misses and other cache issues
- Callgrind – an extension of Cachegrind with extra information on call graphs
- Massif – a heap profiler that shows which parts of the program use heap over time
- Helgrind – a thread debugger, which helps with data race issues
- DRD – a lighter, limited version of Helgrind
valgrind 除了命令行之外还按照顺序读取以下配置:
- 家目录下的
~/.valgrindrc
文件 $VALGRIND_OPTS
环境变量- 当前路径的
.valgrindrc
文件,并且 “will only be considered if it belongs to the current user, is a regular file, and isn’t marked as world-writable"。
Memcheck
可以把 valgrind 作为一个自定义的 target 加入到 CMake 工程中。
Memcheck-Cover
一个可以将 valgrind 输出文件用 html 显示出来的软件。