曲径通幽论坛

标题: make 的 -f 参数以及在 Makefile 文件间传递参数 [打印本页]

作者: beyes    时间: 2011-4-18 11:46
标题: make 的 -f 参数以及在 Makefile 文件间传递参数
make 的 -f 参数后接文件名(可含路径),由该文件名指定的文件作为 Makefile 文件,并且这个文件名后可接参数,该参数可作为该文件中的某个变量。

某个目录下文件:
[beyes@SLinux temp]$ ll
total 8
-rw-rw-r--. 1 beyes beyes  103 Apr 18 11:00 Makefile
drwxrwxr-x. 2 beyes beyes 4096 Apr 18 11:01 scripts
[beyes@SLinux temp]$ ll scripts/
total 8
-rw-rw-r--. 1 beyes beyes 74 Apr 18 10:49 Kbuild.include
-rw-rw-r--. 1 beyes beyes 37 Apr 18 10:49 Makefile.building


其中 Makefile 文件的内容为:
include ./scripts/Kbuild.include

all:
        @make $(build)="pass init for another Makefile\'s parameter"

上面,$(build) 变量在 scripts/Kbuild.include 文件中有定义,所以这里要在第 1 行将 Kbuild.include 包含进来。Kbuild.include 中的内容为:
build := -f ./scripts/Makefile.building obj


所以,我们在执行 make 时,实际上就是展开以下命令:
make -f ./scripts/Makefile.building obj="pass init for another Makefile\'s parameter"

上面 obj= 后面的双引号中的 's 前要加一反斜杠表示字符转义,否则会在 make 时发生语法错误。这里,我们指定 scripts/Makefile.building 作为另一个 Makefile 文件,并且要向它传递进一个 obj 参数,这个参数的内容就是双引号里的字符串。

Makefile.building 文件内容如下所示:
src := $(obj)

output:
    @echo $(src)

上面,我们将 $(obj) 的内容赋给 src 这个变量,并在最后显示这个变量。

现在 make 一下,看输出内容:
[beyes@SLinux temp]$ make
make[1]: Entering directory `/home/beyes/Makefile/temp'
pass init for another Makefile's parameter
make[1]: Leaving directory `/home/beyes/Makefile/temp'

正确输出。

总结一下 make 的过程:
在主 Makefile 文件中,因为仅有一个目标 all,所以就只要简单执行 make 命令即可,它通过 -f 参数指定了要 make 另外一个 Makefile 文件(Makefile.building),并且要向那个文件传递进一个 obj 变量参数。这时,我们的 make 流程转入到 Makefile.building 中,因为该文件中亦只有一个目标,所以默认下也就执行该目标下的命令,即打印出传递进来的参数内容。

在 Linux 内核的 Makefile 中,在研究 bzImage  的生成过程,也会看到如上所经历的过程。

另外,还可以通过 export 关键字将参数导出到当前工作的环境变量中,这样子 Makefile 也能使用这些变量。但是如果子 Makefile 中含有同名变量的话,那么就以子 Makefile 中的变量为准,这和 C 语言中的局部变量是同一个道理。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2