cunit-testingmakefile

How to create test executables in Makefile in C?


I want to build make test with Makefile, and the test target should generate <file_name>_test executable based on the folder tests/<file_name>.c. All tests/*.c files have a main() function.

If there are 3 files under tests, then 3 executables should be generated; if there are 10 files, then 10 should be generated.

Here is the project structure:

./Makefile

./src
./src/hello.c
./src/hello.h
./src/world.c
./src/world.h
./src/(many_other_modules).c
./src/(many_other_modules).h

./tests
./tests/hello.c
./tests/world.c
./tests/(many_other_modules).c

Here is the Makefile:

CC = gcc
CFLAGS = -Wall -g
SOURCES = $(wildcard tests/*.c)

test:
    // How to gernate "hello_test" and "world_test" and other "(many_other_modules)_test" executables in Makefile?

How to write the test rule in Makefile for generating all test executables?


Solution

  • You need a pattern rule that can create your test executables from their respective sources. For example:

    %_test.o: tests/%.c
        $(COMPILE.c) %(OUTPUT_OPTION) $<
    

    (Alternatively, just add tests to your VPATH and rename the sources with the _test suffix.)

    Then your test target needs to depend on all of these:

    test: %(patsubst tests/%.c,%_test,$(SOURCES))