bob2
bob2

Reputation: 1112

How to pass parameters to a makefile recipe, or resolve variables at parse time

I'm dealing with a rather complex makefile system, and I'd like to be able to either pass parameters to a recipe, or have variables in a recipe resolved at parsing time, rather than when executed. Here's a simplified example of of what's going on.

Makefile

all : dep_chain

MYVAR := hello
include depchain.mk

MYVAR := world
include depchain.mk

dep_chain : $(DEPCHAIN)

depchain.mk

$(MYVAR) : $(DEPCHAIN)
    @echo $(MYVAR)

DEPCHAIN := $(MYVAR)

I'd like this to print

hello
world

instead of

world
world

In other words, in the recipe @echo $(MYVAR), I'd like $(MYVAR) to resolve when it is parsed. Or perhaps someone knows another way of passing the value of a variable that may change later to the recipe.

EDIT:

The fix to make this work, as solved by MadScientist, is to change depchain.mk as follows.

depchain.mk

$(MYVAR) : MYVAR := $(MYVAR)

$(MYVAR) : $(DEPCHAIN)
    @echo $(MYVAR)

DEPCHAIN:= $(MYVAR)

Upvotes: 2

Views: 1581

Answers (1)

MadScientist
MadScientist

Reputation: 100856

Well, I'm assuming that your example is not really a good representation of your actual requirements, because if you really just want to get the name of the target you can use automatic variables ($@) for that:

$(MYVAR): $(DEPCHAIN)
        @echo $@

In general there are two ways to handle this. The first is constructed variable names, like this:

hello_MYVAR = foo
world_MYVAR = bar

$(MYVAR): $(DEPCHAIN)
        @echo $($@_MYVAR)

The second is target-specific variables, like this:

hello: MYVAR = foo
world: MYVAR = bar

$(MYVAR): $(DEPCHAIN)
        @echo $(MYVAR)

If these are not sufficient you'll have to be more forthcoming about your real requirements and restrictions.

Upvotes: 3

Related Questions