我的程序接收命令行参数。
我希望我的 Makefile 能够处理如下参数:
make run arg1 arg2 arg3
或
make debug arg1 arg2 arg3
在我的 Makefile 中,我使用这个答案中建议的方法。 第一个版本是
# Description of variables
# If the first argument is "run" or "debug"...
ifeq (run,$(firstword $(MAKECMDGOALS)))
# use the rest as arguments for "run"
ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS))
# ...and turn them into do-nothing targets
$(eval $(ARGS):;@:)
else ifeq (debug,$(firstword $(MAKECMDGOALS)))
# use the rest as arguments for "run"
ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS))
# ...and turn them into do-nothing targets
$(eval $(ARGS):;@:)
endif
all: $(EXECUTABLE)
# The rest of the Makefile
效果很好。
为了消除代码重复,我决定描述该函数
parse_args
:
# Description of variables
# Function to parse command line arguments
define parse_args
# Extract the rest of the arguments after the first one
$(eval ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS)))
# ...and turn them into do-nothing targets
$(eval $(ARGS):;@:)
endef
# If the first argument is "run" or "debug"...
ifeq (run,$(firstword $(MAKECMDGOALS)))
$(call parse_args)
else ifeq (debug,$(firstword $(MAKECMDGOALS)))
$(call parse_args)
endif
# The rest of the Makefile
但是这个版本的代码会产生错误:
:~/c/database_binary_and_hash_search$ make debug file add apple
Makefile:109: *** recipe commences before first target. Stop.
也许有人可以解释为什么代码会这样?
也许有人可以解释为什么代码会这样?
恐怕这是一个乏味的解释。一旦
make
看到一行开始
使用选项卡时,它会认为该行位于配方上下文中,并且您有选项卡
您不希望 make
出现在菜谱上下文中。 这个答案
可能误导了您,因为它有双空格缩进,但实际上不是制表符。
像这样重写来解决这个问题:
$ cat Makefile
# Function to parse command line arguments
define parse_args
# Extract the rest of the arguments after the first one
$(eval ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS)))
$(eval $(ARGS):;@:))
endef
# If the first argument is "run" or "debug"...
ifeq (run,$(firstword $(MAKECMDGOALS)))
$(call $(parse_args))
else ifeq (debug,$(firstword $(MAKECMDGOALS)))
$(call $(parse_args))
endif
.PHONY: run debug
run:
@echo running with args $(ARGS)
debug:
@echo debugging with args $(ARGS)
这给你:
$ make run a b c
running with args a b c
$ make debug x y z
debugging with args x y z
$ make
running with args
$ make debug
debugging with args
$ make x
make: *** No rule to make target 'x'. Stop.