I have a small project that builds a number of targets from the same source files. The targets require building the source files with different compile flags. This is actually on cygwin so I'll use that as the concrete example although I suppose this is a generic problem.
So this would be an example Makefile:
a: CFLAGS =
a: a.o c.o
b: CFLAGS = -mno-cygwin
b: b.o c.o
This works in principle, building a will compile with CFLAGS unset, and building b will compile with CFLAGS set to -mno-cygwin. But only if c.o does not already exist.
So doing
> make a b
in a virgin directory will first compile a.c and c.c using an empty CFLAGS. Then it will try to build b using CFLAGS=-mno-cygwin. But since c.o already exists it will not recompile c.c resulting in linker errors since object files need to have the same setting of this flag.
Again, the cygwin-flag is just one concrete example, and I am looking for a generic solution.
What I have tried is to introduce an extra target checking the current CFLAGS and remove all object files if it does not match:
ARCH = `echo $(CFLAGS)`
checkTarget:
-@if test "`cat .arch`" != "$(ARCH)"; then \
rm *.o; \
/bin/echo -n $(ARCH) > .arch; \
fi
Inserting this target as a dependency for the two targets ensures that all object files are recompiled if required.
a: CFLAGS =
a: checkTarget a.o c.o
b: CFLAGS = -mno-cygwin
b: checkTarget b.o c.o
This however recompiles every object file, which is unnecessary, and becomes a problem in a larger project.
Is there a better way to do this?
EDIT: In the comments to the single answer included a hint that you could make the object files depend on the content of the CFLAGS. I can't figure out how to do that, except cat'ing them to a temporary file and compare to the previous ones and then copy that over a depending file. Is there no better way?