I have a list defined in the make file and the user is supposed to set an environment variable which I need to find in this list. Is there a way using gnu make to do this? I want to do this outside any recipe, before make starts building any targets. It is a QA check to make sure user sets the env. variable to a value within a range/list.
On terminal:
setenv ENV_PARAM x
In Makefile:
PARAMS := a b c
if ${ENV_PARAM} exists in $(PARAMS)
true
else
false
endif
@MadScientist's answer works. Is there a way to wrap the if block with a foreach loop to test multiple parameters?
KEYS := PARAMS FACTORS
PARAMS := a b c
FACTORS := x y z
foreach v in ($(KEYS)) {
ifneq ($(filter $(ENV_$(v)),$(v)),)
$(info $(ENV_$(v)) exists in $(v))
else
$(info $(ENV_$(v)) does not exist in $(v))
endif
}
You can use the filter
function to do this:
PARAMS := a b c
ifneq ($(filter $(ENV_PARAM),$(PARAMS)),)
$(info $(ENV_PARAM) exists in $(PARAMS))
else
$(info $(ENV_PARAM) does not exist in $(PARAMS))
endif
Read: "if the result of searching for the ENV_PARAM value in PARAMS is not empty, run the 'true' block else run the 'false' block".
UPDATE
Your second question really cannot be answered fully with the information you've provided. In order to know the best way to do it we need to know what you are really going to do inside the if-statement, when the condition is true and when it is false. Are you going to declare more variables? Create some rules? Something else? There are many ways to do what you want and the cleanest one may be different depending on what you want to do.
However, a general solution would involve using define
to create the content of the loop, then using foreach
and eval
, something like this:
KEYS := PARAMS FACTORS
PARAMS := a b c
FACTORS := x y z
define LOOPBODY
ifneq ($$(filter $$(ENV_$(v)),$(v)),)
$$(info $$(ENV_$(v)) exists in $(v))
else
$$(info $$(ENV_$(v)) does not exist in $(v))
endif
endef
$(foreach v,$(KEYS),$(eval $(LOOPBODY)))
You might be interested in a set of posts I made regarding metaprogramming in GNU make: http://make.mad-scientist.net/category/metaprogramming/