在Ubuntu上使用GCC進行代碼覆蓋率分析,通常需要借助gcov
和lcov
工具。以下是詳細步驟:
首先,確保你已經安裝了gcc
、gcov
和lcov
。你可以使用以下命令來安裝它們:
sudo apt update
sudo apt install gcc gcov lcov
使用gcc
編譯你的C或C++代碼,并啟用覆蓋率選項。對于C代碼,可以使用-fprofile-arcs
和-ftest-coverage
選項;對于C++代碼,可以使用相同的選項。
例如,假設你的源文件是main.c
,你可以這樣編譯:
gcc -fprofile-arcs -ftest-coverage -o main main.c
對于C++代碼,假設你的源文件是main.cpp
,你可以這樣編譯:
g++ -fprofile-arcs -ftest-coverage -o main main.cpp
運行編譯后的程序。這將生成覆蓋率數據文件(.gcda
和.gcno
文件)。
./main
使用lcov
工具生成覆蓋率報告。首先,創建一個目錄來存放覆蓋率數據:
mkdir coverage
然后,使用lcov
收集覆蓋率數據并生成HTML報告:
lcov --capture --directory . --output-file coverage/coverage.info
genhtml coverage/coverage.info --output-directory coverage/html
打開生成的HTML報告,通常在coverage/html
目錄下。你可以使用瀏覽器打開index.html
文件來查看詳細的覆蓋率報告。
xdg-open coverage/html/index.html
假設你有一個簡單的C程序main.c
:
#include <stdio.h>
int main() {
int a = 1;
int b = 2;
int c = a + b;
printf("Result: %d\n", c);
return 0;
}
按照上述步驟進行編譯、運行和生成報告:
gcc -fprofile-arcs -ftest-coverage -o main main.c
./main
mkdir coverage
lcov --capture --directory . --output-file coverage/coverage.info
genhtml coverage/coverage.info --output-directory coverage/html
xdg-open coverage/html/index.html
這樣,你就可以在瀏覽器中查看詳細的代碼覆蓋率報告了。