Home > front end >  Makefile: How to run certain prereq recipe depending on target?
Makefile: How to run certain prereq recipe depending on target?

Time:02-25

OBJLIST1=foo.o bar.o baz.o
    
target1: $(OBJLIST1)
    $(CC) $(CFLAGS) -c $^ -o $@

$(OBJLIST1) : $(OBJLIST1:%.o=%.c)
    $(CC) $(CFLAGS) -c $^ -o $@

target1-i: $(OBJLIST1)
    $(CC) $(CFLAGS) -c $^ -o $@

$(OBJLIST1) : $(OBJLIST1:%.o=%.c)
    $(CC) $(CFLAGS) -DSOME_MACRO -c $^ -o $@

I need to be able to compile list of object files differently depending on the target i call. I have no idea how to do that tbh, this is giving me a bunch of errors like "overriding recipe for target...", "ignoring old recipe for target...". How can i specify which recipe i want to call in a target command? Apparently the order doesn't change much.

CodePudding user response:

You can use target specific variables to set relevant variables.

The example below shows how to add EXTRA_FLAGS to the target1-i target.

OBJLIST1=foo.o bar.o baz.o

target1: $(OBJLIST1)
    $(CC) $(CFLAGS) -c $^ -o $@

target1-i: EXTRA_FLAGS=-DSOME_MACRO
target1-i: $(OBJLIST1)
    $(CC) $(CFLAGS) -c $^ -o $@

$(OBJLIST1) : $(OBJLIST1:%.o=%.c)
    $(CC) $(CFLAGS) $(EXTRA_FLAGS) -c $^ -o $@

CodePudding user response:

You're trying to have the same object file built in two different ways. This is ambiguous (see my comment in @kaylum's answer). I would try something like:

SOURCES=foo.c bar.c baz.c

%_1.o : %.c
    $(CC) $(CFLAGS) -c $^ -o $@

%_2.o : %.c
    $(CC) $(CFLAGS) -DSOME_MACRO -c $^ -o $@

target1: $(SOURCES:%.c=%_1.o)
    $(CC) $(CFLAGS) -c $^ -o $@

target2: $(SOURCES:%.c=%_2.o)
    $(CC) $(CFLAGS) -c $^ -o $@

which gives you:

$ make -n target1
cc  -c foo.c -o foo_1.o
cc  -c bar.c -o bar_1.o
cc  -c baz.c -o baz_1.o
cc  -c foo_1.o bar_1.o baz_1.o -o target1

$ make -n target2
cc  -DSOME_MACRO -c foo.c -o foo_2.o
cc  -DSOME_MACRO -c bar.c -o bar_2.o
cc  -DSOME_MACRO -c baz.c -o baz_2.o
cc  -c foo_2.o bar_2.o baz_2.o -o target2
  • Related