Sample project showing how to use sanitizers and analyzers to check C++ code.
Example platform is Linux/Ubuntu using GCC:
sudo apt-get update
sudo apt-get install build-essential cmake cppcheck clang-format clang-tidy valgrind
pip install gcovr
Enable extensive compiler warnings-as-errors with the custom cmake option ENABLE_WARNINGS
.
cmake -DCMAKE_BUILD_TYPE=Release -DENABLE_WARNINGS=ON ..
cmake --build . -j
Use cppcheck with the compile_commands.json
file generated by cmake.
cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ..
cppcheck --project=compile_commands.json --cppcheck-build-dir=./temp/cppcheck --error-exitcode=1 --enable=all
Use clang-format to check the code style.
clang-format --dry-run -Werror --style=file src/bad_code.cpp
Use clang-tidy to analyze code patterns.
Clang tidy can be used by cmake via CXX_CLANG_TIDY enabled with:
cmake -DENABLE_CLANG_TIDY=ON ..
cmake --build .
Use the AddressSanitizer to check for memory issues at runtime.
cmake -DENABLE_ASAN=ON ..
cmake --build .
ctest --output-on-failure
Use the UndefinedBehaviorSanitizer to check for cases of undefined behaviour at runtime.
Enable and run with:
cmake -DCMAKE_BUILD_TYPE=Debug -DENABLE_UBSAN=ON ..
cmake --build . -j
ctest --output-on-failure
Use Valgrind to check for memory issues at runtime.
cmake -DUSE_VALGRIND=ON ..
cmake --build .
ctest -T memcheck --output-on-failure
Create a coverage report using gcovr to see how much of the code is executed during tests.
cmake -DENABLE_COVERAGE=ON ..
cmake --build . -j
ctest
cd ..
gcovr -r . --html --html-details -o build/coverage/coverage.html