WeezyKrush
WeezyKrush

Reputation: 494

How to make Makefile Variables persist between commands

Here is a sample makefile that demonstrates what I'm trying to accomplish:

PLATFORM=wrongName

debug:
    @echo debug $(PLATFORM)

debug-android: android debug

android:PLATFORM=android
android:
    @echo set PLATFORM to $(PLATFORM)

here is the terminal output:

user:~/Project/maketest$ make debug-android
set PLATFORM to android
debug wrongName

when calling the target make debug-android my intention is to set the PLATFORM variable to "android", and that works in the android: command, however the "PLATFORM" var reverts to "wrongName" default value set at the top of the makefile. I'm trying to replace the value here so that any subsequent dependencies for the target will also see the value of "PLATFORM" as "android". so my question is: how do i make "PLATFORM" variable assignment persist between commands/targets?

Upvotes: 1

Views: 640

Answers (2)

Beta
Beta

Reputation: 99094

There are a couple of different ways to do this, but you still haven't made clear exactly what you want these rules to do, conceptually.

Here is one way:

debug-android:PLATFORM=android
debug-android: android debug

android:
    @echo set PLATFORM to $(PLATFORM)

EDIT:

Ah, so the idea is to avoid repetition of PLATFORM=android. Try this:

PLATFORM=wrongName

all: debug-android prod-android test-android

debug:
    @echo Debug $(PLATFORM)

prod:
    @echo Prod $(PLATFORM)

test:
    @echo Test $(PLATFORM)

%-android: PLATFORM=android

debug-android: debug
test-android: test
prod-android: prod

If this is on the right track, we can go farther, removing the redundancy of those last three lines.

Upvotes: 2

MadScientist
MadScientist

Reputation: 100856

In general, it's a bad idea to do this. Most of the time if you want to do it, it probably means that you should be thinking about the problem differently.

However, it is possible to do this (in GNU make only) using eval. Usually when I see eval used in a recipe it's a code smell but it does work:

android:
        $(eval PLATFORM := $(PLATFORM))
        @echo set PLATFORM to $(PLATFORM)

Upvotes: 1

Related Questions