1 2 3 // Code to create coverage example 4 /* Steps to compare a single file 5 1. g++ -O0 --coverage sample.cpp 6 This should create sample.cpp.gcno (and a.out) 7 2. Run a.out 8 This should create sample.cpp.gcda 9 3. Run gcov -b sample.cpp.gcda 10 This should create sample.cpp.gcov 11 4. Run python read-gcov.py -a test sample.cpp.gcov to ensure that read/write 12 of gcov files works correctly. 13 14 Steps to create a unit-test-like file and compare 15 1. Make directories base/, unit/, and diff/ 16 2. Move previous sample.cpp.gcov file to base/ directory 17 3. Remove sample.cpp.gcda 18 4. g++ -O0 -DUNIT --coverage sample.cpp -o sample_unit 19 5. Run sample_unit 20 6. Run gcov -b sample.cpp.gcda 21 7. Move sample.cpp to unit/ directory 22 8. Use the 'diff' action to generate text-based comparisons and summaries: 23 python compare_gcov.py --action diff --base-dir base --unit-dir unit 24 25 9. Use the 'compare' action to create comparison gcov files: 26 python compare_gcov.py --action compare --base-dir base --unit-dir unit --output-dir diff 27 Now there should be sample.cpp.gcov in the diff/ directory. 28 The code in func5 (and the call site) should be listed as uncovered. 29 */ 30 31 32 // Should be listed as unexecutable code 33 #if 0 34 int unused_func() 35 { 36 int i = 1; 37 return i; 38 } 39 #endif 40 func1()41int func1() 42 { 43 int j = 0; 44 int k = 0; 45 for (int i = 0; i < 10; i++) { 46 if (i < 5) { // branch coverage 47 j += 4; 48 } 49 k += i; 50 } 51 return k; 52 } 53 54 // Should be uncovered func2()55void func2() 56 { 57 int i = 1; 58 int j = i+2; 59 } 60 func3(bool should_throw)61int func3(bool should_throw) 62 { 63 if (should_throw) { 64 throw "An exception"; 65 } 66 return 3; 67 } 68 func4(int i)69void func4(int i) 70 { 71 int j = 0; 72 try { 73 j = func3(false); 74 } catch (...) { 75 j = 3; 76 } 77 78 } 79 80 // covered in base, uncovered in unit func5(int i)81void func5(int i) 82 { 83 int j = i+1; 84 } 85 86 main()87int main() 88 { 89 int k = func1(); 90 // Should not be executed, so func2 is uncovered 91 if (k < 0) { 92 func2(); 93 } 94 func4(0); 95 #ifndef UNIT 96 func5(1); 97 #endif 98 return 0; 99 } 100