Makefile条件中的多个if语句

Cau*_*arz 4 makefile

生成文档说,复杂条件的语法如下:

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
Run Code Online (Sandbox Code Playgroud)

但是我不明白如何使用这种语法来重写以下代码:

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: ;
Run Code Online (Sandbox Code Playgroud)

boy*_*all 5

使用您的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)
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

$ make
Makefile:4: Extraneous text after `else' directive
Makefile:6: *** commands commence before first target.  Stop.
Run Code Online (Sandbox Code Playgroud)

根据@MadScientist的建议编辑makefile(即之后的空格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)
Run Code Online (Sandbox Code Playgroud)

我得到:

$ make
Makefile:9: *** commands commence before first target.  Stop.
Run Code Online (Sandbox Code Playgroud)

就是说,除非它是规则的一部分,否则您不能使用命令。如果要记录类似的内容,请尝试以下操作:

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
Run Code Online (Sandbox Code Playgroud)

由此,我得到:

$ make
CC is mipsel-linux-gcc
foo
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参见https://www.gnu.org/software/make/manual/html_node/Make-Control-Functions.html#index-error-$(info ...)如果需要,可以将其放在条件语句中,但是为什么要这样做?:->


Max*_*kin 5

恕我直言,ifeq语句占用太多空间,更难打字和阅读。更好的选择:

CC.1 := gcc
CC.2 := clang
CC := $(or ${CC.${option}},mipsel-linux-gcc)
$(info "Using ${CC}")
Run Code Online (Sandbox Code Playgroud)