I have the files main.c, version1.c, version2.c and header.h
version1.c and version2.c are two different implementations of the same header file (header.h), and this header file is used by main.c.
Now, I want to
$ make v1
cc -c main.c
cc -c version1.c
cc -o prog main.o version1.o
or
$ make v2
cc -c main.c
cc -c version2.c
cc -o prog main.o version2.o
depending on which version of code I’m using.
I tried Conditionally appending to a variable inside a Makefile target and wrote
.PHONY: v1 v2
OBJ = main.o
v1: OBJ += version1.o
v2: OBJ += version2.o
v1 v2: prog
prog: $(OBJ)
cc -o prog $(OBJ)
%.o: %.c header.h
cc -c $<
But this quite simply does not work:
$ make v1
cc -c main.c
cc -o prog main.o version1.o
cc: version1.o: No such file or directory
make: *** [prog] Error 1
it seems that make evaluates $(OBJ) before the append when it appears in the dependency list, but after it when it appears in the command list.
Is this a bug in make? Or am I just doing it wrong? How do I do this correctly?
The target-specific modification of the variable (
v1: OBJ += version1.o) applies in the body of the rule, not in the prerequisite list. Here’s how I’d do it: