makefile

Makefile: automatic target in other directories


in a current C project we've had the bad idea of putting all object files to a different folder from the source. It wasn't complicated to manage at first, but now we need to compile some files in a specific folder and others in another.

The arborecence looks like:

After running make I'd like the arborescence to be modified as:

At first the makefile was like:

CSRC = $(wildcard *.c)
OBJS = $(CSRC:%.c=%.o)

objs1/%.o : %.c
  gcc -c -o $@ $<

Now there's also file2.c and it should not be compiled in objs1, file1.o should be in both objs1 and objs2 and file2.o should be in objs2.

I use generic rules because the project is bigger and it is really convenient.

So I have two variables which contains the name of objects, one for objs1, the other for objs2.

I'd like to do something like

$(OBJS1): %.o %.c

But it would act like source files are in objs1 and that's not the case.

So what's the way to combine generic rules with specified location?

Thank you


Solution

  • You'll probably want to specify the objects manually seeing as you need specific files compiled in specific directories:

    objs1 := objs1/file1.o
    objs2 := objs2/file1.o objs2/file2.o
    
    $(objs1): CFLAGS += blah1
    $(objs2): CFLAGS += blah2
    
    $(objs1): objs1/%.o: src/%.c
    $(objs2): objs2/%.o: src/%.c
    
    $(objs1) $(objs2):
        $(COMPILE.c) $(OUTPUT_OPTION) $<
    

    If the small amount of duplication is annoying you, you can use secondary expansion instead

    .SECONDEXPANSION:
    $(objs1) $(objs2): %.o: src/$$(notdir $$*).c
        $(COMPILE.c) $(OUTPUT_OPTION) $<