Marcus
Marcus

Reputation: 5

Testing command in Makefile

I have written some functions in C and I want to compile them with a Makefile.

Before compiling I want to make a command to test them with another command and then compile them only if they passed the tests.

What I am thinking about :

tests :
   gcc tests.c
all : tests
   gcc *.c

I want to compile the tests.c and then if they are OK to compile all the functions.

How can I do this ? Thank you very much

Upvotes: 1

Views: 1097

Answers (1)

Dima Tisnek
Dima Tisnek

Reputation: 11779

General outline for building realproduct only after tests pass:

all: realproduct

realproduct: | run-tests

run-tests: tests
        ./$<

How does it work?

there's an implicit rules to compile tests.c into tests executable, it will run cc tests.c -o tests and you can modify it with CFLAGS, LDFLAGS, LDLIBS variables.

$< means first dependency, and ./ is a path to it, so it means run tests executable from local directory

| is placed before "order-only dependency", which means that run-tests must be "made" before realproduct, but run-tests is not part of "buildin" realproduct. Thus, cc realproduct.c -o realproduct will be invoked to build.

So, in summary, whenever tests.c is changed, first tests will be built, then ./tests will be ran, then realproduct will be built:

$ make
cc     tests.c   -o tests
./tests
cc     realproduct.c   -o realproduct

Finally you can use https://www.gnu.org/software/make/manual/html_node/Phony-Targets.html to make sure some commands are always ran, not only when dependencies have changed.

Upvotes: 1

Related Questions