无法从Makefile调用函数

问题描述

我需要从make目标调用一个函数,该函数将被多次调用

define generate_file
if [ "${RQM_SETUP}" = "ci" ]; then
    echo "$1" > $(2).txt
else
    echo "It is Not Setup";
fi
endef
all:
        $(call generate_file,John Doe,101)
        $(call generate_file,Peter Pan,102)

现在我陷入了这个错误

bash-5.0# make
if [ "" = "ci" ]; then
/bin/sh: Syntax error: unexpected end of file (expecting "fi")
make: *** [Makefile:10: all] Error 2

解决方法

您的函数是多行,它将尝试作为单独的Shell调用执行。这将失败,因为任何单行本身在语法上都不正确。您可以通过将其设置为一行来使它起作用,即:

$ cat Makefile
define generate_file
if [ "${RQM_SETUP}" = "ci" ]; then \
    echo "$1" > $(2).txt; \
else \
    echo "It is Not Setup"; \
fi
endef
all:
        $(call generate_file,John Doe,101)
        $(call generate_file,Peter Pan,102)

输出:

$ make
if [ "" = "ci" ]; then echo "John Doe" > 101.txt; else echo "It is Not Setup"; fi
It is Not Setup
if [ "" = "ci" ]; then echo "Peter Pan" > 102.txt; else echo "It is Not Setup"; fi
It is Not Setup