如何从make目标手动调用另一个目标?

Sim*_*ter 31 gnu-make

我想要一个像这样的makefile:

cudaLib :
    # Create shared library with nvcc

ocelotLib :
    # Create shared library for gpuocelot

build-cuda : cudaLib
    make build

build-ocelot : ocelotLib
    make build

build :
    # build and link with the shared library
Run Code Online (Sandbox Code Playgroud)

*Lib任务创建一个直接在设备上运行cuda的库,或者分别在gpuocelot上运行cuda.

对于这两个构建任务,我需要运行相同的构建步骤,只创建库不同.

是否有替代直接运行make?

make build
Run Code Online (Sandbox Code Playgroud)

有什么后必备条件?

mkl*_*nt0 59

注意:此答案侧重于给定makefile中不同目标的强大递归调用方面.

为了补充Jack Kelly的有用答案,这里是一个GNU makefile片段,演示了$(MAKE)如何在同一个makefile中强健地调用不同的目标(确保make调用相同的二进制文件,并且定位相同的makefile):

# Determine this makefile's path.
# Be sure to place this BEFORE `include` directives, if any.
THIS_FILE := $(lastword $(MAKEFILE_LIST))

target:
    @echo $@  # print target name
    @$(MAKE) -f $(THIS_FILE) other-target # invoke other target

other-target:
    @echo $@ # print target name
Run Code Online (Sandbox Code Playgroud)

输出:

$ make target

target
other-target
Run Code Online (Sandbox Code Playgroud)

使用$(lastword $(MAKEFILE_LIST))-f ...确保该$(MAKE)命令使用相同的makefile,即使-f ...在最初调用make时使用显式路径()传递该makefile也是如此.


注意:虽然GNU make确实具有递归调用的功能 - 例如,变量$(MAKE)专门用于启用它们 - 它们的重点是调用从属 makefile,而不是调用同一 makefile中的不同目标.

也就是说,即使上面的解决方法有点麻烦和模糊,它确实使用常规功能,应该是健壮的.

以下是涉及递归调用("sub-make")的手册部分的链接:


Jac*_*lly 26

大多数make版本都设置了一个$(MAKE)可用于递归调用的变量.


bob*_*ogo 11

正如你所写,build目标将需要做一些不同的事情,这取决于你是否刚刚完成了ocelot或cuda构建.这是另一种说法必须以build某种方式进行参数化的方式.我建议使用相关变量来创建单独的构建目标(就像您已经拥有的那样).就像是:

build-cuda: cudaLib
build-ocelot: ocelotLib

build-cuda build-ocelot:
    shell commands
    which invoke ${opts-$@}
Run Code Online (Sandbox Code Playgroud)

在命令行中键入make build-cuda(例如).制作第一个版本cudaLib,然后执行配方build-cuda.它在调用shell之前扩展宏.$@在这种情况下build-cuda,因此${opts-$@}首先扩展到${opts-build-cuda}.现在继续扩展${opts-build-cuda}.你将在makefile的其他地方定义opts-build-cuda(当然还有它的姐妹opts-build-ocelot).

PS build-cuda等等.人.不是真正的文件,你最好告诉make this(.PHONY: build-cuda).

  • 你调用_build_cuda_(`make build_cuda`).Make将尽职尽责地为`cudaLib`执行shell命令,然后执行`build-cuda`的shell命令.在生成最后一组命令的过程中,make必须扩展变量`opts-build-cuda`.(大概你可以有其他的变量,比如`deptool-build-cuda`或`build-cuda-output-dir`等等.)这允许你在Makefile中编写一个看起来完全不同的命令块.传递到shell.PS总是用`--warn-undefined-variable`调用make,它会为你节省很多心痛. (2认同)