gnu make - 如何根据某些条件在{fore}中定义变量

时间:2016-11-22 23:05:16

标签: makefile gnu-make

我想根据某些条件在foreach循环中分配变量。

例如在实践中我想用它来浏览所有必需的工具(gcc g ++ as ld)检查它们是否在系统路径中找到。如果是,则保留它,如果没有,则尝试添加用户提供的路径前缀,如果可以在那里找到,则修改变量以使用完整路径,否则向用户报告早期错误。

1 个答案:

答案 0 :(得分:0)

总的来说,我想出了:

TEST_ARRAY = AA BB
K := $(foreach myTest,$(TEST_ARRAY),\
        $(if $(filter AA,$(myTest)),\
            $(eval $(myTest) := match),\
            $(eval $(myTest) := mismatch)))

$(info "AA: ${AA}")
$(info "BB: ${BB}")

输出是:

"AA: match"
"BB: mismatch"

回答我更具体的问题是相当长的 - 工作代码片段是这样的:

#on widows
DEVNUL := NUL
WHICH := where
#on linux
#DEVNUL := /dev/null
#WHICH := which

# set path to be searched when command is not found in system PATH
GNU_PATH := c:\NSS\GNU_Tools_ARM_Embedded\5.4 2016q3\bin2
# optionally set command prefix - for example all your tools are not called "gcc" but "arm-gcc" so you would fill here "arm-" 
GNU_PREFIX := arm-none-eabi-
# set command suffix - for example on windows all executable files have suffix ".exe" 
GNU_SUFFIX := .exe

# escape spaces in path because make $(wildcard ) can not handle them :(
empty :=
space := $(empty) $(empty)
GNU_PATH_ESCAPED := $(subst  $(space),\ ,$(GNU_PATH))

# define used tool-chain commands
CC              := gccx
AS              := as
AR              := ar
LD              := ld
NM              := nm
OBJDUMP         := objdump
OBJCOPY         := objcopy
SIZE            := size

# detect if tool-chain commands are installed and fill correct path (prefer system PATH, then try to find them in suggested GNU_PATH)
# if not found on neither system path nor on user provided GNU_PATH then early error is reported to user
EXECUTABLES = CC AS AR LD NM OBJDUMP OBJCOPY SIZE
$(foreach myTestCommand,$(EXECUTABLES),\
    $(if $(shell ${WHICH} ${GNU_PREFIX}$($(myTestCommand)) 2>${DEVNUL} ),\
        $(eval $(myTestCommand) := ${GNU_PREFIX}$($(myTestCommand))),\
        $(if $(wildcard $(GNU_PATH_ESCAPED)\${GNU_PREFIX}$($(myTestCommand))$(GNU_SUFFIX)),\
            $(eval $(myTestCommand) := '$(GNU_PATH)/${GNU_PREFIX}$($(myTestCommand))$(GNU_SUFFIX)'),\
            $(error "Can not find tool ${GNU_PREFIX}$($(myTestCommand))$(GNU_SUFFIX), either make in in your system PATH or provide correct path in variable GNU_PATH"))))

# just print what tools will be used
$(foreach myTestCommand,$(EXECUTABLES),\
    $(info found tool $($(myTestCommand))))

default:
    @$(CC) --version

在我的测试用例中,我的路径上除了gccx之外的所有工具,GNU_PATH位于found tool 'c:\NSS\GNU_Tools_ARM_Embedded\5.4 2016q3\bin2/arm-none-eabi-gccx.exe' found tool arm-none-eabi-as found tool arm-none-eabi-ar found tool arm-none-eabi-ld found tool arm-none-eabi-nm found tool arm-none-eabi-objdump found tool arm-none-eabi-objcopy found tool arm-none-eabi-size 中提供的用户文件夹中。

isActive = true