Search code examples
makefilegnu-make

Define multiple GNU Makefile variables from $(shell...)


I have a file (e.g. iostruct.def) with some variable definitions in it:

VARIABLE_A=/some/path
VARIABLE_B=/another/path
...

I want to read this file from a GNU Makefile, prefix all paths by some string (e.g. /tmp) and use them as normal Make variables. Here is my (failed) attempt on this:

vars := $(shell sed -r "s|=(\/.*)|=/tmp\1|" iostruct.def)
$(eval $(foreach v,$(vars),$(v)))
all:
    @echo $(VARIABLE_A)
    @echo $(VARIABLE_B)

However I end up with VARIABLE_A="/tmp/some/path VARIABLE_B=/tmp/another/path" and VARIABLE_B is empty. What am I doing wrong?

PS. The emphasis is on the on-the-fly definition of multiple Make variables coming from $(shell ...); the tmp prefixing of values is just an example.


Solution

  • One easy to understand solution is to convert the iostruct.def file using shell commands into the format you want, then include that file. Like this:

    all:
            @echo $(VARIABLE_A)
            @echo $(VARIABLE_B)
    
    include iostruct.def.mk
    
    iostruct.def.mk: iostruct.def
            sed -r 's|=(\/.*)|=/tmp\1|' $< > $@
    

    For more details see Remaking Makefiles in the GNU Make manual.