Makefile problem with conditional used in define used in commands part of a rule
-
04-07-2019 - |
Question
I have a section of makefile that has this sort of structure:
bob:
ifdef DEBUG
@echo running
endif
@echo chug chug chug
ifdef DEBUG
@echo done
endif
bobit:
@echo "before"
@make bob
@echo "after"
I'm simplifying greatly here, all the echo's are actually non trivial blocks of commands and there is more conditional stuff, but this captures the essence of my problem.
For technical reasons I don't want to get into right now, I need to get rid of that submake, but because the echo's represent nontrivial amounts of code I don't want to just copy and past the body of bob in place of the submake.
Ideally what I'd like to do is something like this
define BOB_BODY
ifdef DEBUG
@echo running
endif
@echo chug chug chug
ifdef DEBUG
@echo done
endif
endef
bob:
$(BOB_BODY)
bobit:
@echo "before"
$(BOB_BODY)
@echo "after"
Unfortunately the conditionals seem to be shafting me, they produce "ifdef: Command not found" errors, I tried getting around this with various combinations of eval and call, but can't seem to figure out a way to get it to work.
How do I make this work? and is it even the right way to approach the problem?
Solution
The way I have fixed this is to use bash conditionals instead, which actually makes a certain amount of sense since we are playing with commands and not make rules.
So my ideal solution from above becomes something like
define BOB_BODY
@if [[ -n "$(DEBUG)" ]]; then \
echo running; \
fi;
@echo chug chug chug
@if [[ -n "$(DEBUG)" ]]; then \
echo done; \
fi
endef
bob:
$(BOB_BODY)
bobit:
@echo "before"
$(BOB_BODY)
@echo "after"
OTHER TIPS
You can simply change the order of ifdef/define:
ifdef DEBUG
define BOB_BODY
@echo running
@echo chug chug chug
@echo done
endef
else
define BOB_BODY
@echo chug chug chug
endef
endif
UPDATE
define CHUG
@echo chug chug chug
endef
ifdef DEBUG
define BOB_BODY
@echo running
$(CHUG)
@echo done
endef
else
define BOB_BODY
$(CHUG)
endef
endif