简体   繁体   中英

Read environment variable in make file

I have a environment variable set with name $MY_ENV_VARIABLE.

How do I use this variable inside my makefile to (for example) include some source files?

LOCAL_SRC_FILES = $(MY_ENV_VARIABLE)/libDEMO.so

Something like above doesn't seem to work.

Note: in my case this is needed for building with the Android NDK but I guess this applies to make in general.

Just to add some information...

The syntax to access the environment variable in make is like other variables in make...

#export the variable. e.g. in the terminal,
export MY_ENV_VARIABLE="hello world"

...

#in the makefile (replace before call)
echo $(MY_ENV_VARIABLE)

This performs the substitution before executing the commmand. If you instead, want the substitution to happen during the command execution, you need to escape the $ (For example, echo $MY_ENV_VARIABLE is incorrect and will attempt to substitute the variable M in make, and append it to Y_ENV_VARIABLE )...

#in the makefile (replace during call)
echo $$MY_ENV_VARIABLE

Make sure you exported the variable from your shell. Running:

echo $MY_ENV_VARIABLE

shows you whether it's set in your shell. But to know whether you've exported it so that subshells and other sub-commands (like make) can see it try running:

env | grep MY_ENV_VARIABLE

If it's not there, be sure to run export MY_ENV_VARIABLE before running make.

That's all you need to do: make automatically imports all environment variables as make variables when it starts up.

I just had a similar issue (under Cygwin):

  • Running echo $OSTYPE on the shell prints the value, but
  • running env | grep OSTYPE env | grep OSTYPE doesn't give any output.

As I can't guarantee that this variable is export ed on all machines I want to run that makefile on, I used the following to get the variable from within the makefile:

OSTYPE = $(shell echo $$OSTYPE)

Which of course can also be used within a condition like the following:

ifeq ($(shell echo $$OSTYPE),cygwin)
# ...do something...
else
# ...do something else...
endif

EDIT:

Some things I found after experimenting with the info from jozxyqk's answer , all from within the makefile:

  • If I run @echo $$OSTYPE or @echo "$$OSTYPE" in a recipe, the variable is successfully expanded into cygwin .
  • However, using that in a condition like ifeq ($$OSTYPE,cygwin) or ifeq ("$$OSTYPE","cygwin") doesn't expand it.
  • Thus it is logical that first setting a variable like TEST = "$$OSTYPE" will lead to echo $(TEST) printing cygwin (the expansion is done by the echo call) but that doesn't work in a condition - ifeq ($(TEST),cygwin) is false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM