Nishikant
Nishikant

Reputation: 95

exporting env variables from a common target to all targets in Makefile

I have a common target with setting a bunch of env variables something like this in Makefile

# file common.mk
setup :
    export LD_LIBRARY_PATH=${MY_HOME}/LIBS:${LD_LIBRARY_PATH}
    export MY_VERSION=2.2
    ...

Now I want to use these variables in all make targets

#file Makefile

include ${MY_RUN_DIR}/common.mk
run : setup
    # export all the variables 
    # do domething

Now when I do make run I cannot see the variables being set. It is because all the variables are set only in "setup" target. I have like 100s of Makefile where I will have to add all the export variables and I would prefer to add only one line instead to export all variables.

How can I export variables from one target to all targets wherever I want?

Upvotes: 1

Views: 1382

Answers (2)

Antonio
Antonio

Reputation: 61

If you want to do that properly as you described above, you may do this with such boilerplate script:

do_something:
    @echo do_something
    @echo $(VAR1)
    @echo $(VAR2)


setup:
    export VAR1=var1 && \
    export VAR2=var2  && \
    $(MAKE) do_something

Upvotes: 1

Beta
Beta

Reputation: 99094

Just don't put the assignments in a rule:

# file common.mk

export LD_LIBRARY_PATH=${MY_HOME}/LIBS:${LD_LIBRARY_PATH}
export MY_VERSION=2.2
...

and don't bother with the prerequisite setup:

#file Makefile

include ${MY_RUN_DIR}/common.mk
run:
#  do something, such as
    @echo my version is $$MY_VERSION

Upvotes: 1

Related Questions