Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read environment variable in make file

Tags:

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.

like image 598
Sander Versluys Avatar asked May 31 '13 08:05

Sander Versluys


People also ask

How do I get env variables in makefile?

Unfortunately, Makefile doesn't automatically have access to the root . env file, which might look something like this. That said, we can include the appropriate environment file in our Makefile . The environment variables are then accessible using the $(VAR_NAME) syntax.

Are makefile variables environment variables?

Variables in make can come from the environment in which make is run. Every environment variable that make sees when it starts up is transformed into a make variable with the same name and value. However, an explicit assignment in the makefile, or with a command argument, overrides the environment.

How do I print an environment variable in makefile?

To use it, just set the list of variables to print on the command line, and include the debug target: $ make V="USERNAME SHELL" debug makefile:2: USERNAME = Owner makefile:2: SHELL = /bin/sh.exe make: debug is up to date. Now you can print variables by simply listing them on the command line.


2 Answers

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
like image 77
jozxyqk Avatar answered Oct 21 '22 19:10

jozxyqk


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.

like image 45
MadScientist Avatar answered Oct 21 '22 19:10

MadScientist