rix
rix

Reputation: 10632

Export env var in make file so it's available to sub make files

I have the following rule in a top level makefile. I want to set an environment variable at this level so it's shell accessible for all sub make rules.

How is this done please?

get:
    for i in $(STACK_DIRS) ; do \
        cd $(CURDIR)/$${i} && make get ; \
    done \

Upvotes: 0

Views: 1131

Answers (1)

tripleee
tripleee

Reputation: 189337

The shell command to export a variable is export.

get:
    for i in $(STACK_DIRS) ; do \
        foo="bar"; export foo; cd $(CURDIR)/$${i} && make get ; \
    done

Though you might as well just say

get:
    for i in $(STACK_DIRS) ; do \
        cd $(CURDIR)/$${i} && make foo="bar" get ; \
    done

A much more idiomatic way to do this is to run each target separately. We create .$i.get_done for each $i like this:

.PHONY: get
get: $(patsubst %,.%.get_done,$(STACK_DIRS))
.%.get_done:
    cd $(CURDIR)/$* && make foo="bar" get

Now if .ick.get_done exists, it means that get was run in the subdirectory ick and if it is newer than all of its dependencies, it does not need to be remade.

Upvotes: 1

Related Questions