Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you conditionally call a target based on a target variable (Makefile)?

I want a different version of the clean target to run based on whether make dev or make prod are run on a makefile.

I'm not compiling anything per se, just want to conditionally call a particular target or set of targets based on a variable, for example:

ifeq ($(BUILD_ENV),"development")
clean: -clean
else
clean: -clean-info
endif

#---------------------------------
dev: BUILD_ENV = development
dev: dev-setup which-env

#---------------------------------
prod: BUILD_ENV = production
prod: prod-setup which-env

#---------------------------------


which-env: clean
    @echo -e "$(GREEN)$(BUILD_ENV)!$(CLEAR)"

-clean: -clean-info -clean-logs | silent
    @echo -e "$(GREEN)</CLEAN>$(CLEAR)"

-clean-info:
    @echo -e "$(GREEN)<CLEAN>...$(CLEAR)"

-clean-logs:
    @echo -e " $(GREY)Removing log and status files $(CLEAR)";
    @if [ -d .stat ]; then rm -rf .stat; fi
    @rm -f *.log || true

Is there a way to do this with Makefiles? I havent found anything yet that illustrates this use-case.

I'm not trying to specifically clean anything or build anything this is just an example of me trying to conditionally call a set of targets. The actual targets could be anything else.

like image 940
qodeninja Avatar asked Sep 30 '13 22:09

qodeninja


People also ask

How do I add a condition in makefile?

Syntax of Conditionals Directives The text-if-true may be any lines of text, to be considered as part of the makefile if the condition is true. If the condition is false, no text is used instead. If the condition is true, text-if-true is used; otherwise, text-if-false is used.

How do I write an if statement in makefile?

If the condition is true, make reads the lines of the text-if-true as part of the makefile; if the condition is false, make ignores those lines completely. It follows that syntactic units of the makefile, such as rules, may safely be split across the beginning or the end of the conditional.

How do I use IFEQ in makefile?

The ifeq directive begins the conditional, and specifies the condition. It contains two arguments, separated by a comma and surrounded by parentheses. Variable substitution is performed on both arguments and then they are compared.


1 Answers

It's not at all clear that what you're asking for is really what you want, but here goes:

all:

ifeq ($(BUILD_ENV),development)
all: clean-dev
else
all: clean-other
endif

clean-dev:
    @echo running $@, doing something

clean-other:
    @echo running $@, doing something else

If you run make BUILD_ENV=development, you'll get something; if you run make or make BUILD_ENV=production you'll get something else.

like image 121
Beta Avatar answered Oct 23 '22 15:10

Beta