我使用Makefiles。

我有一个名为run的目标,它运行构建目标。简化后,如下图所示:

prog: ....
  ...

run: prog
  ./prog

有传递参数的方法吗?这

make run asdf --> ./prog asdf
make run the dog kicked the cat --> ./prog the dog kicked the cat

当前回答

下面是另一个解决方案,可以帮助解决其中一些用例:

test-%:
    $(PYTHON) run-tests.py $@

换句话说,选择一些前缀(在本例中是test-),然后将目标名称直接传递给程序/运行程序。我想,如果涉及到一些运行脚本,可以将目标名称展开为对底层程序有用的内容,那么这是非常有用的。

其他回答

你可以像下面这样将变量传递给Makefile:

run:
    @echo ./prog $$FOO

用法:

$ make run FOO="the dog kicked the cat"
./prog the dog kicked the cat

or:

$ FOO="the dog kicked the cat" make run
./prog the dog kicked the cat

或者使用Beta提供的解决方案:

run:
    @echo ./prog $(filter-out $@,$(MAKECMDGOALS))
%:
    @:

%: -匹配任何任务名称的规则; @: -空食谱=什么都不做

用法:

$ make run the dog kicked the cat
./prog the dog kicked the cat

它已经有一段时间了,但我将提供我在生产中使用的版本。

我希望有人会觉得它有用。

例子:

.PHONY: greeting
greeting:
    echo $(if $s,$s,)

命令:

使问候s="hello world"

输出:

你好世界

这个问题已经提了三年了,但是不管怎样……

如果您正在使用GNU make,这很容易做到。唯一的问题是make会将命令行中的非选项参数解释为目标。解决办法是把他们变成什么都不做的目标,这样make就不会抱怨:

# If the first argument is "run"...
ifeq (run,$(firstword $(MAKECMDGOALS)))
  # use the rest as arguments for "run"
  RUN_ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS))
  # ...and turn them into do-nothing targets
  $(eval $(RUN_ARGS):;@:)
endif

prog: # ...
    # ...

.PHONY: run
run : prog
    @echo prog $(RUN_ARGS)

运行这个函数会得到:

$ make run foo bar baz
prog foo bar baz

您可以显式地提取命令行中的第n个参数。要做到这一点,你可以使用变量MAKECMDGOALS,它保存给'make'的命令行参数列表,它将其解释为目标列表。如果你想提取第n个参数,你可以使用该变量与"word"函数结合使用,例如,如果你想要第二个参数,你可以将它存储在一个变量中,如下所示:

second_argument := $(word 2, $(MAKECMDGOALS) )

Run: ./prog看起来有点奇怪,因为正确的部分应该是一个先决条件,所以Run: prog看起来更好。

我的建议很简单:

.PHONY: run

run:
    prog $(arg1)

我想补充一点,可以传递参数:

作为参数:使arg1="asdf"运行 或者定义为environment: arg1="asdf" make run