Search code examples
makefilegnu-make

How to correctly prefix a list of dependencies in a Makefile rule?


My Makefile has rules that apply to every subdirectory. When one such rule has dependencies, I obviously want those dependencies to

  1. When mentioned in the dependencies, they should bind to the same path as the target file.
  2. When mentioned in the rule, they should use the same path as the target.

The best that I can come up with is the example below. It works, but looks verbose and hard to read. Is there a more programatic way of approaching this?

BUILDDIR = build
BCFILES = file1.bc file2.bc file3.bc 

...

BCFILES_STARED = $(patsubst %, */$(BUILDDIR)/%, $(BCFILES))
*/$(BUILDDIR)/my_program.bc: $(BCFILES_STARED) */build
    llvm-link $(patsubst %, $(@D)/%, $(BCFILES)) -o $@

Solution

  • I'm really not clear on what you want to do. But maybe it's something like:

    BUILDDIR = build
    BCFILES = file1.bc file2.bc file3.bc 
    
    SUBDIRS := $(wildcard */.)
    PROGRAMS := $(patsubst %/.,%/$(BUILDDIR)/my_program.bc,$(SUBDIRS))
    
    all: $(PROGRAMS)
    
    .SECONDEXPANSION:
    
    %/my_program.bc: $$(addprefix $$(@D)/,$$(BCFILES))
              @mkdir -p $(@D)
              llvm-link $^ -o $@
    

    You can look in the GNU Make manual for details on wildcard and secondary expansion.