VinayakaB
VinayakaB

Reputation: 63

Why is variable not getting set in Makefile?

This is my Makefile.

ifeq ($(BRANCH), )
    BRANCH := $(shell git rev-parse --abbrev-ref HEAD)
endif
ifeq ($(COMMIT), )
    COMMIT := $(shell git rev-parse --abbrev-ref HEAD)
endif

all:
ifeq ($(BRANCH), )
    $(error Please pass a valid branch)
endif
ifeq ($(COMMIT), )
    $(error Please pass a valid commit)
endif
    echo $(BRANCH) $(COMMIT)
    rm -f server-test

I want user to be able to pass the arguments BRANCH and COMMIT using the make command and set it to the default value if the user doesn't pass those arguments. This works if I use make or make BRANCH=master. But if the user uses make BRANCH= or make BRANCH="", it gives an error. The part I don't understand is I am using the same check for setting the variable and throwing the error. Why is it going inside the if block in one place and not the other?

I am trying to conditionally set a variable to default if the user didn't pass it to the Makefile

Upvotes: 1

Views: 630

Answers (1)

Beta
Beta

Reputation: 99172

The trouble is that this:

BRANCH := $(shell ...)

Doesn't work as you expect. From the manual page:

If a variable has been set with a command argument,
then ordinary assignments in the makefile are ignored.

So if you run make BRANCH= or make BRANCH="", then you have set the value of that variable -- to an empty string. It remains empty when you try to assign a new value to it, and triggers the error. The solution is on the same page:

override BRANCH := $(shell ...)

Upvotes: 4

Related Questions