Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple if statements in makefile conditionals

Tags:

makefile

The make documentation says the syntax of a complex conditional is as follows:

conditional-directive-one
text-if-one-is-true
else conditional-directive-two
text-if-two-is-true
else
text-if-one-and-two-are-false
endif

But I don't understand how to use this syntax to rewrite the following piece of code:

ifeq ($(option), 1)
CC=gcc
@echo use gcc
else ifeq($(option), 2)
CC=clang
@echo use clang
else
CC=mipsel-linux-gcc
@echo use mipsel-linux-gcc
endif

#first target
foo: ;
like image 866
Cauchy Schwarz Avatar asked Oct 24 '16 11:10

Cauchy Schwarz


2 Answers

Using your makefile:

ifeq ($(option), 1)
    CC=gcc
    @echo use gcc
else ifeq($(option), 2)
    CC=clang
    @echo use clang
else
    CC=mipsel-linux-gcc
    @echo use mipsel-linux-gcc
endif

#first target
foo:
    echo CC $(CC)

I get the following error:

$ make
Makefile:4: Extraneous text after `else' directive
Makefile:6: *** commands commence before first target.  Stop.

Editing the makefile as per suggestion from @MadScientist (i.e. a space after the ifeq):

ifeq ($(option), 1)
    CC=gcc
    @echo use gcc
else ifeq ($(option), 2)
    CC=clang
    @echo use clang
else
    CC=mipsel-linux-gcc
    @echo use mipsel-linux-gcc
endif

#first target
foo:
    echo CC $(CC)

I get:

$ make
Makefile:9: *** commands commence before first target.  Stop.

This is saying you can't use a command unless it's part of a rule. If you want to log something like that, try it like this:

ifeq ($(option), 1)
    CC=gcc
else ifeq ($(option), 2)
    CC=clang
else
    CC=mipsel-linux-gcc
endif

$(info CC is $(CC))

#first target
foo:
    @echo foo

From this, I get:

$ make
CC is mipsel-linux-gcc
foo

See https://www.gnu.org/software/make/manual/html_node/Make-Control-Functions.html#index-error for more info on $(info ...) - you can put it inside the conditionals if you want, but why would you? :->

like image 164
boyvinall Avatar answered Oct 16 '22 17:10

boyvinall


IMHO, ifeq statements take too much space, harder to type and read. A better alternative:

CC.1 := gcc
CC.2 := clang
CC := $(or ${CC.${option}},mipsel-linux-gcc)
$(info "Using ${CC}")
like image 37
Maxim Egorushkin Avatar answered Oct 16 '22 18:10

Maxim Egorushkin