sudo apt-get install cpputest(版本較舊)。./configure && make,直接使用編譯產出的庫與頭文件。// sample.h
struct Student { char* name; int score; };
void ret_void(void);
int ret_int(int, int);
double ret_double(double, double);
char* ret_pchar(char*, char*);
struct Student* init_student(struct Student*, char*, int);
用 #ifndef CPPUTEST 隔離 main,便於測試編譯時排除。
// test.c
#include <CppUTest/CommandLineTestRunner.h>
#include <CppUTest/TestHarness.h>
extern "C" { #include "sample.h" }
TEST_GROUP(sample) {
void setup() { printf("測試開始...\n"); }
void teardown() { printf("測試結束...\n"); }
};
TEST(sample, ret_int_success) {
CHECK_EQUAL(3, ret_int(1,2));
}
TEST(sample, ret_int_failed) {
CHECK_EQUAL(4, ret_int(1,2)); // 故意失敗
}
int main(int argc, char* argv[]) {
return CommandLineTestRunner::RunAllTests(argc, argv);
}
| 宏 | 用途 |
|---|---|
| CHECK(cond) | 條件為真通過 |
| CHECK_EQUAL(exp, act) | 期望值==實際值 |
| STRCMP_EQUAL(exp, act) | 字串比較 |
| LONGS_EQUAL(exp, act) | 長整數比較 |
| DOUBLES_EQUAL(exp, act, tol) | 浮點數容差比較 |
| POINTERS_EQUAL(exp, act) | 指針比較 |
| FAIL(msg) | 強制失敗 |
CPPUTEST_HOME = /path/to/cpputest
CC = gcc
CPP = g++
CFLAGS = -g -Wall -std=c99 -D CPPUTEST
CPPFLAGS = -g -Wall -I$(CPPUTEST_HOME)/include
LDFLAGS = -L$(CPPUTEST_HOME)/lib -lCppUTest
MEMFLAGS = -include $(CPPUTEST_HOME)/include/CppUTest/MemoryLeakDetectorMallocMacros.h
test: test.o sample.o
$(CPP) -o $@ $^ $(LDFLAGS)
test.o: test.c
$(CPP) -c $< $(CPPFLAGS) $(MEMFLAGS)
sample.o: sample.c
$(CC) -c $< $(CFLAGS) $(MEMFLAGS)
./test:默認運行。-c:彩色輸出。-v:詳細模式。-r N:重複運行 N 次。-g GROUP:指定群組。-n TEST:指定單個測試。編譯時加入 MEMFLAGS,測試代碼中故意 malloc 不 free,輸出將精確定位洩漏文件、行號、大小與堆棧內容。