Skip to content

Instantly share code, notes, and snippets.

@newhouseb
Created September 23, 2010 06:16
Show Gist options
  • Save newhouseb/593214 to your computer and use it in GitHub Desktop.
Save newhouseb/593214 to your computer and use it in GitHub Desktop.
Makefile Unit Tests
test_file:
echo "#include <stdio.h>" > test.c
awk '/^bool test_(.*)\(\)/ {print "extern bool", $$2, ";"}' *.c >> test.c
echo "int unit_test(){ bool pass; int cases = 0, passes = 0;" >> test.c
awk '/^bool test_(.*)\(\)/ {print "pass =",$$2,"; printf(\"%s", $$2, "\\n\", pass ? \"PASSED\" : \"FAILED\"); cases += 1; if(pass) passes++;"}' *.c >> test.c
echo "printf(\"%i of %i cases PASSED\n\", passes, cases);}" >> test.c
test: CFLAGS += -Dmain\(args...\)="* a_; extern int unit_test(); main() { unit_test(); } int b_(args)" test.c
test: EXECUTABLE = test
test: test_file all
./$(EXECUTABLE)
@newhouseb
Copy link
Author

Example Makefile

CC = g++
CFLAGS = -g
EXECUTABLE = main
SOURCE_FILES = main.c

all:
    $(CC) $(SOURCE_FILES) $(CFLAGS) -o $(EXECUTABLE)

include maketest

main.c:
#include <stdio.h>

int main() {
    printf("hello world\n");
}

bool test_pass() {
    return true;
}

bool test_fail() {
    return false;
}

Running make && ./main
hello world

Running make test
PASSED test_pass()
FAILED test_fail()
1 of 2 cases PASSED

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment