2

At the top of my Makefile, before any of the rules, I have the following:

ifeq ($(ENVIRONMENT),LOCAL)
    TARGET := local_target
else
    TARGET := hello
endif

If the ENVIRONMENT environment variable is not set, or is set to a value other than LOCAL, instead of setting TARGET to hello, I want the makefile to halt and exit with -1.

Can I do that?? When I change TARGET := hello to exit -1, I get the following error:

Makefile:4: *** missing separator.  Stop.

How can I make this work??

JFMR
  • 23,265
  • 4
  • 52
  • 76
Saqib Ali
  • 11,931
  • 41
  • 133
  • 272

1 Answers1

4

exit is a shell command, so you could use the shell assignment operator (i.e.: !=) inside the Makefile to call exit:

TARGET != exit -1

This would be actually equivalent to:

TARGET := $(shell exit -1)

Note again that this calls a shell that in turns runs the shell's exit built-in, i.e.: it does not exit make. The typical approach for exiting while processing a makefile is to call GNU Make's error built-in function instead:

$(error Error-message-here)

Putting everything together:

ifeq ($(ENVIRONMENT),LOCAL)
 TARGET := local_target
else # indent with spaces, not a tab
 $(error ENVIRONMENT not set to LOCAL)
endif
JFMR
  • 23,265
  • 4
  • 52
  • 76
  • 2
    Tip: do not put a tab before `$(error .....)`, otherwise make will complain that `recipe commences before first target`. Either do not indent at all or indent with spaces. – harmic Feb 18 '19 at 05:00
  • @harmic Thank you very much. I guess indenting `$(error ...)` with a single space as it is in the current edit, will discourage a reader from using a tab. For consistency, I've kept the same indentation in the variable assignment, even though it does not suffer from that problem. – JFMR Feb 18 '19 at 07:26