将 bash 脚本嵌入到 makefile 中

amp*_*ier 1 linux bash ubuntu gcc makefile

我想在 makefile 中包含一些条件语句:

SHELL=/bin/bash
all: 
        $(g++ -Wall main.cpp othersrc.cpp -o hello)
        @if [[ $? -ne -1 ]]; then \
          echo "Compile failed!"; \
          exit 1; \
        fi
Run Code Online (Sandbox Code Playgroud)

但得到一个错误:

/bin/bash: -c: 第 0 行:需要条件二元运算符 /bin/bash: -c: 第 0 行:-1' /bin/bash: -c: line 0:if [[ -ne -1 ]] 附近的语法错误;然后 \' makefile:3: 目标 'all' 的配方失败 make: *** [all] 错误 1

如何修复它?

Max*_*kin 5

请注意,makefile 配方的每一行都在不同的 shell 中运行,因此$?前一行不可用,除非您使用.ONESHELLoption。

修复没有.ONESHELL

all: hello
.PHONY: all

hello: main.cpp othersrc.cpp
    g++ -o $@ -Wall main.cpp othersrc.cpp && echo "Compile succeeded." || (echo "Compile failed!"; false)
Run Code Online (Sandbox Code Playgroud)

.ONESHELL

all: hello
.PHONY: all

SHELL:=/bin/bash
.ONESHELL:

hello:
    @echo "g++ -o $@ -Wall main.cpp othersrc.cpp"
    g++ -o $@ -Wall main.cpp othersrc.cpp
    if [[ $$? -eq 0 ]]; then
        echo "Compile succeded!"
    else
        echo "Compile failed!"
        exit 1
    fi
Run Code Online (Sandbox Code Playgroud)

$需要传递到 shell 命令时,必须像$$在 makefile 中一样引用它(make基本上传递一美元会收取一美元费用)。因此$$?

  • 如果您使用 .ONESHELL,则不需要反斜杠。如果您不想使用 .ONESHELL (请注意,仅在 GNU make 4.0 及更高版本中可用),那么使用反斜杠就足够了,您不需要 .ONESHELL (但您必须在末尾添加 `; \` `g++` 行也是如此)。 (2认同)