Static Analysis in C++: Enforce Quality with Clang-Tidy & Cppcheck [#41-1]
이 글의 핵심
Catch bugs before runtime: clang-tidy + Cppcheck, compile_commands.json, and CI gates.
Introduction: catch bugs before you run
Static analysis inspects source without executing it. Clang-Tidy provides hundreds of checks for modern C++, performance, and bugprone patterns. Cppcheck is compiler-independent and strong on memory, null derefs, and bounds issues. Together they complement each other.
Covers: scenarios, .clang-tidy, compile_commands.json, representative checks, --fix, Cppcheck flags/suppressions, CI workflows, incremental analysis, adoption strategy.
Table of contents
- Why static analysis
- Clang-Tidy
- Cppcheck
- Complete demo project
- Common errors
- CI integration
- Production patterns
- Summary
1. Why static analysis
Production crashes from null derefs, use-after-move, range-for copies, magic numbers—many are detectable statically when configured.
flowchart LR
A[Compile] --> B[Clang-Tidy]
A --> C[Cppcheck]
B --> D[Gate merge]
C --> D
2. Clang-Tidy
Checks: 'bugprone-*,modernize-use-nullptr,performance-for-range-copy'
WarningsAsErrors: ''
HeaderFilterRegex: '.*'
Generate compile_commands.json:
cmake -B build -S . -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
clang-tidy -p build src/*.cpp
Use --fix carefully with tests.
3. Cppcheck
cppcheck --enable=all --suppress=missingIncludeSystem -I include --error-exitcode=1 -j8 src/
4. Demo project
Check in CMakeLists.txt, a sample .clang-tidy, and run-static-analysis.sh alongside your project for reproducible CI runs.
5. Common errors
- Missing
compile_commands.json→ configure CMake with export. - Too many diagnostics on legacy code → enable gradually, NOLINT sparingly, exclude
third_partyviaHeaderFilterRegex.
6. CI
Run clang-tidy + cppcheck on PRs; optional: changed-files-only for speed.
7. Production patterns
Pre-commit hooks, clangd in-editor, split warnings-as-errors by check category.
8. Summary
| Tool | Focus |
|---|---|
| Clang-Tidy | Modern C++, performance, many autofixes |
| Cppcheck | Memory, control flow without full compilation |
Next: ASan/TSan (#41-2)
Previous: Docker for C++ (#40-3)
Keywords
clang-tidy, cppcheck, static analysis, compile_commands.json, CI quality