30

I have a target inside a makefile:

all: $(TARGETS)

I want a variant that differs from all only by the fact that it sets an environment variable. Something like:

all-abc: $(TARGETS)
    ABC=123

but that doesn't work because the dependencies are processed before the variable is set. I've thought about having another dependency before the real ones that just sets the environment variable but I don't think the environment persists across targets. That is to say that

abc:
    ABC=123
all-abc: abc $(TARGETS)

doesn't work. What I ultimately want to be able to do is

$ make all-abc

instead of

$ ABC=123 make

Is it possible to set an environment variable like this ?

(GNU Make 3.82)

2
  • What's wrong with make all ABC=123? Commented Mar 5, 2013 at 17:51
  • 3
    prefer not to have to worry about the values to set the variables to (i.e. in the example I don't want to have to remember 123) Commented Mar 5, 2013 at 18:09

1 Answer 1

48

try this:

all:
    @#usual rule, if you call `make all-abc`, this will print "123"
    @echo $(ABC)

all-abc: ABC=123
all-abc: all
    @#what you put here it's going to be executed after the rule `all`
Sign up to request clarification or add additional context in comments.

4 Comments

yes that's good. I didn't think of adding two targets with the same name. Good one!
starfry: I don't think you're understanding what this does exactly. You should read the section of the GNU make manual on target-specific variables.
To add to what @MadScientist said: there are not two targets with the same name here. "all-abc: ABC=123" defines a target-specific variable; it is not a target. gnu.org/software/make/manual/html_node/Target_002dspecific.html
I use xargs within a target command, and I needed to do all-abc: export ABC=123 to make the variable accessible from the command executed by xargs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.