Search code examples
makefilewildcardsubdirectoryrules

make rule for no extension from wildcard subdirectory


I have a bunch of targets that are built with the same type of make rule:

   env GOARCH=amd64 GOOS=linux go build -ldflags="-s -w" -o bin/foo foo/*.go
   env GOARCH=amd64 GOOS=linux go build -ldflags="-s -w" -o bin/bar bar/*.go
   env GOARCH=amd64 GOOS=linux go build -ldflags="-s -w" -o bin/hello hello/*.go
   env GOARCH=amd64 GOOS=linux go build -ldflags="-s -w" -o bin/world world/*.go

and I was trying to write one generic rule, based on

Here is what I come up so far (but not working):

DIRS =$(filter %/, $(wildcard */))

build: $(DIRS)
    export GO111MODULE=on

bin/%: %/$(wildcard *.go)
    env GOARCH=amd64 GOOS=linux go build -ldflags="-s -w" -o bin/$@ $@/*.go

Solution

  • First we use wildcard to find all files whose names end in .go:

    FILES := $(wildcard */*.go)
    
    $(info Files are $(FILES)) # displays the contents of FILES, for debugging
    

    Then we remove the file names, strip the trailing slashes and prepend bin/ by means of patsubst:

    TARGS := $(patsubst %/, bin/%,$(dir $(FILES)))
    

    We write a PHONY all rule that requires all of these targets:

    .PHONY: all
    all: $(TARGS)
    

    and a pattern rule to build them, using automatic variables:

    bin/%:
        env GOARCH=amd64 GOOS=linux go build -ldflags="-s -w" -o $@ $*/*.go