11

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?

Community
  • 1
  • 1
phoenix
  • 7,988
  • 6
  • 39
  • 45
  • You could probably get what you want by using a custom target and using `clang --build --target `. But why waste your time? Just use a wrapper around the two `scan-build` steps. – nega Feb 22 '17 at 18:28
  • I also like `cmake --build` because it keeps all of the generated files nicely tucked away in a folder rather than putting them all in the root of the project. – phoenix Feb 22 '17 at 19:07
  • you have control over that too w/o using `--build`. i keep my source and build directories side-by-side. then you can just do `cd myproj/build; cmake ../src/` – nega Feb 22 '17 at 19:38
  • You should anyway use out-of-source builds. Having files in your source directory isn't a good argument. – usr1234567 Feb 22 '17 at 20:26

1 Answers1

5

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.

Alex Reinking
  • 16,724
  • 5
  • 52
  • 86