$npx -y skills add gadievron/raptor --skill gcov-coverageAdd gcov code coverage instrumentation to C/C++ projects
| 1 | # Code Coverage with gcov |
| 2 | |
| 3 | ## Purpose |
| 4 | Instrument C/C++ programs with gcov to measure test coverage. |
| 5 | |
| 6 | ## How It Works |
| 7 | |
| 8 | ### Build with Coverage |
| 9 | ```bash |
| 10 | gcc --coverage -o program source.c |
| 11 | ``` |
| 12 | |
| 13 | ### Run Program |
| 14 | ```bash |
| 15 | ./program |
| 16 | # Creates .gcda files with execution data |
| 17 | ``` |
| 18 | |
| 19 | ### Generate Reports |
| 20 | |
| 21 | **Text report:** |
| 22 | ```bash |
| 23 | gcov source.c |
| 24 | # Creates source.c.gcov with line-by-line coverage |
| 25 | ``` |
| 26 | |
| 27 | **HTML report:** |
| 28 | ```bash |
| 29 | gcovr --html-details -o coverage.html |
| 30 | ``` |
| 31 | |
| 32 | ## Coverage Flags |
| 33 | |
| 34 | - `--coverage` (shorthand for `-fprofile-arcs -ftest-coverage -lgcov`) |
| 35 | - Add to both `CFLAGS` and `LDFLAGS` |
| 36 | |
| 37 | ## Build System Integration |
| 38 | |
| 39 | ### Makefile |
| 40 | ```makefile |
| 41 | ENABLE_COVERAGE ?= 0 |
| 42 | ifeq ($(ENABLE_COVERAGE),1) |
| 43 | CFLAGS += --coverage |
| 44 | LDFLAGS += --coverage |
| 45 | endif |
| 46 | ``` |
| 47 | |
| 48 | ### CMake |
| 49 | ```cmake |
| 50 | option(ENABLE_COVERAGE "Enable coverage" OFF) |
| 51 | if(ENABLE_COVERAGE) |
| 52 | add_compile_options(--coverage) |
| 53 | add_link_options(--coverage) |
| 54 | endif() |
| 55 | ``` |
| 56 | |
| 57 | ## When User Requests Coverage |
| 58 | |
| 59 | ### Steps |
| 60 | 1. Detect build system (Makefile/CMake/other) |
| 61 | 2. Add `--coverage` to CFLAGS and LDFLAGS |
| 62 | 3. Clean previous build: `make clean` or `rm -f *.gcda *.gcno` |
| 63 | 4. Build with coverage: `make ENABLE_COVERAGE=1` or `cmake -DENABLE_COVERAGE=ON` |
| 64 | 5. Run tests: `make test` or `./test_suite` |
| 65 | 6. Generate report: `gcovr --html-details coverage.html --print-summary` |
| 66 | 7. Present summary and path to HTML report |
| 67 | |
| 68 | ## Output |
| 69 | |
| 70 | **Text (.gcov files):** |
| 71 | ``` |
| 72 | -: 0:Source:main.c |
| 73 | 5: 42: int x = 10; |
| 74 | #####: 43: unused_code(); |
| 75 | ``` |
| 76 | - `5:` = executed 5 times |
| 77 | - `#####:` = not executed |
| 78 | - `-:` = non-executable |
| 79 | |
| 80 | **HTML:** Interactive report with color-coded coverage |
| 81 | |
| 82 | ## Metrics |
| 83 | - **Line coverage**: Executed lines / total lines |
| 84 | - **Branch coverage**: Taken branches / total branches |
| 85 | - **Function coverage**: Called functions / total functions |
| 86 | |
| 87 | Target: 80%+ line coverage, 70%+ branch coverage |