I'd like to use the clang static analyzer command line tool scan-build
with the convenience of cmake --build
.
Most of the resources I found online seem to indicate you need a two-step process:
scan-build cmake .
scan-build make
For example for this small example program with a bug that scan-build
catches:
#include <iostream>
int fun() {
int x;
return x; # main.cpp:5:5: warning: Undefined or garbage value returned to caller
}
int main() {
int a = fun();
std::cout << "Hello, World! " << a << std::endl;
}
CMakeLists.txt
:
cmake_minimum_required(VERSION 3.5)
project(test_program)
set(CMAKE_CXX_STANDARD 11)
set(SOURCE_FILES main.cpp)
add_executable(test_program ${SOURCE_FILES})
If I run scan-build cmake --build cmake-build-release/
it does not find the bug, even though the binary is built. Is there anyway to get scan-build
to work in a one step process with CMake?
The Clang Static Analyzer is a source code analysis tool that finds bugs in C, C++, and Objective-C programs. It implements path-sensitive, inter-procedural analysis based on symbolic execution technique.
The scan-build command can be used to analyze an entire project by essentially interposing on a project's build process. This means that to run the analyzer using scan-build, you will use scan-build to analyze the source files compiled by gcc/clang during a project build.
clang-tidy is a clang-based C++ “linter” tool. Its purpose is to provide an extensible framework for diagnosing and fixing typical programming errors, like style violations, interface misuse, or bugs that can be deduced via static analysis.
If you want to use the Clang Static Analyzer, you should just set CMAKE_EXPORT_COMPILE_COMMANDS=YES
. This will create a compilation database that CSA can read. You don't even need to build your project. The file is located at: /path/to/build/compile_commands.json
.
scan-build
is designed for projects that can't create a compilation database themselves.
Then you can run:
analyze-build --cdb /path/to/build/compile_commands.json \
--use-analyzer /path/to/clang \
--output /path/to/output
It's worth noting that clang-tidy
has all of the CSA checks now. You can use this same compilation database technique to run clang-tidy
on your codebase.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With