gcov是一個可用於C/C++的代碼覆蓋工具,是gcc的內建工具。下面介紹一下如何利用gcov來收集代碼覆蓋信息。
想要用gcov收集代碼覆蓋信息,需要在gcc編譯代碼的時候加上這2個選項 “-fprofile-arcs -ftest-coverage”,把這個簡單的程序編譯一下
gcc -fprofile-arcs -ftest-coverage hello.c -o hello
編譯后會得到一個可執行文件hello和hello.gcno文件,當用gcc編譯文件的時候,如果帶有“-ftest-coverage”參數,就會生成這個.gcno文件,它包含了程序塊和行號等信息
接下來可以運行這個hello的程序
./hello 5
./hello 12
運行結束以后會生成一個hello.gcda文件,如果一個可執行文件帶有“-fprofile-arcs”參數編譯出來,並且運行過至少一次,就會生成。這個文件包含了程序基本塊跳轉的信息。接下來可以用gcov生成代碼覆蓋信息:
gcov hello.c
運行結束以后會生成2個文件hello.c.gcov和myfunc.c.gcov。打開看里面的信息:
-: 0:Source:myfunc.c
-: 0:Graph:hello.gcno
-: 0:Data:hello.gcda
-: 0:Runs:1
-: 0:Programs:1
-: 1:#include
-: 2:
-: 3:void test(int count)
1: 4:{
-: 5: int i;
10: 6: for (i = 1; i < count; i++)
-: 7: {
9: 8: if (i % 3 == 0)
3: 9: printf (“%d is divisible by 3 \n”, i);
9: 10: if (i % 11 == 0)
#####: 11: printf (“%d is divisible by 11 \n”, i);
9: 12: if (i % 13 == 0)
#####: 13: printf (“%d is divisible by 13 \n”, i);
-: 14: }
1: 15:}
被標記為#####的代碼行就是沒有被執行過的,代碼覆蓋的信息是正確的,但是讓人去讀這些文字,實在是一個杯具。不用擔心,有另外一個工具叫lcov,可以用程序解析這些晦澀的字符,最終輸出成html格式的報告,很好吧!
lcov -d . -t ‘Hello test’ -o ‘hello_test.info’ -b . -c
指定lcov在當前目錄“.”去找代碼覆蓋的信息,輸出為’hello_test.info’ ,這個hello_test.info是一個中間結果,需要把它用genhtml來處理一下,genhtml是lcov里面的一個工具。
genhtml -o result hello_test.info
指定輸出目錄是 result。一個完整的html報告就生成了,做一個連接,把這個目錄連到隨便一個web server的目錄下,就可以看報告了。
本人的工程是使用了lcov,並使用makefile,主要的用法如下:
在makefile中定義宏文件:
PROFILE
- ifeq ($(PROFILE),1)
- CFLAGS += -fprofile-arcs
- CFLAGS += -ftest-coverage
- CXXFLAGS += -fprofile-arcs
- CXXFLAGS += -ftest-coverage
- LDFLAGS += -fprofile-arcs
- LDFLAGS += -ftest-coverage
- LDFLAGS += -lgcov
- LIBLDFLAGS += -fprofile-arcs
- LIBLDFLAGS += -ftest-coverage
- LIBLDFLAGS += -lgcov
- endif
在編譯的時候打開此宏:PROFILE=1 make rtm DEBUG=0
然后運行后生成*.gcda文件。
使用下面命令生成report:
- lcov -d . -b . -c -o $rtmcovfile >/dev/null
- #sed -i -e 's#/home/mac_ci/hudson/home/jobs/trunk_RTM/workspace/trunk#\.#g' $rtmcovfile
- # - only keep ssTddPs folders in the report
- lcov -r $rtmcovfile "*/SS_MacData/*" -o $rtmcovfile
- lcov -r $rtmcovfile "*/SS_MacPsWmp/*" -o $rtmcovfile
- lcov -r $rtmcovfile "*/ssCommon/*" -o $rtmcovfile
- lcov -r $rtmcovfile "*/ssData/*" -o $rtmcovfile
- lcov -r $rtmcovfile "*/ssDcmPs/*" -o $rtmcovfile
- lcov -r $rtmcovfile "*/ssPsCommon/*" -o $rtmcovfile
- lcov -r $rtmcovfile "*/ssTestModel/*" -o $rtmcovfile
- # - Remove unneeded paths from coverage
- lcov -r $rtmcovfile "/build/ltesdkroot/*" -o $rtmcovfile
- lcov -r $rtmcovfile "*/SC_DSP_Common/*" -o $rtmcovfile
- lcov -r $rtmcovfile "*/C_Test/*" -o $rtmcovfile
- lcov -r $rtmcovfile "*/T_Tools/*" -o $rtmcovfile
- lcov -r $rtmcovfile "*/ENV/*" -o $rtmcovfile
- lcov -r $rtmcovfile "*/I_Interface/*" -o $rtmcovfile
- lcov -r $rtmcovfile "/usr/*" -o $rtmcovfile
- lcov -r $rtmcovfile "/opt/*" -o $rtmcovfile
- mv $rtmcovfile $PROJECT_ROOT/C_Test/SC_MAC/MacLinuxRtm/logs
- cd $PROJECT_ROOT/C_Test/SC_MAC/MacLinuxRtm/logs
- genhtml -o tdd_ut_rtm_tests_coverage $rtmcovfile >/dev/null
測試結果概覽
具體某個文件的覆蓋率