I know you can use if statements like the following in makefiles:
foo: $(objects)
ifeq ($(CC),gcc)
$(CC) -o foo $(objects) $(libs_for_gcc)
else
$(CC) -o foo $(objects) $(normal_libs)
endif
Is there a way to do a conditional replacement like possibly a ternary type operator.
(condition?$(CC):$(CC2)) -o foo $(objects) $(libs_for_gcc)
And if there isn't what would be the most idiomatic way to achieve the example
I added the c++ tag because the question had only 7 views and I figured someone who used c++ might be likely to know the answer,I know this isn't strictly a c++ question(though I am planning to compile c++ with it)
EDIT: looks like there is an if function using this syntax$(if condition,then-part[,else-part])
I'm still a little confused on how it works though
The $(if ...)
function can serve as a ternary operator, as you've discovered. The real question is, how do conditionals (true vs. false) work in GNU make? In GNU make anyplace where a condition (boolean expression) is needed, an empty string is considered false and any other value is considered true.
So, to test whether $(CC)
is the string gcc
, you'll need to use a function that will return an empty value when it isn't, and a non-empty value when it is.
Typically the filter
and filter-out
functions are used for this. Unfortunately it's easiest to use these in such a way that you get the "not equal" result; in other words, using these functions it's much simpler to accurately generate a non-empty string (true) if the string is not gcc
, and an empty string (false) if the value is gcc
. For example:
$(if $(filter-out gcc,$(CC)),$(info is not gcc),$(info is gcc))
If the only effect you are trying to achieve is to use either the one or the other compiler, I think the best way is to use a variable for that special compilation step and set this depending on your condition.
ifeq (condition)
MYCC=$(CC2)
LIBS=$(LIBS_FOR_CC2)
else
MYCC=$(CC)
LIBS=$(LIBS_FOR_CC)
endif
and then later in the rule to compile use
$(MYCC) -o foo $(objects) $(LIBS)
At least this is how I remember structuring the makefiles into a) configuration and b) the rule sets.
Sorry if that doesn't answer your question, but I am not aware of a ternay operator for GNU make (and I presume you are referring to GNU make?).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With