我在 makefile 中使用了 += 并尝试添加更多编译文件:
使左边的文件能正常工作:编译4个.cpp文件。
但是make the right file是不行的,只能编译main.o和xmlutil.o。 因此,echomsg 中的 echo $(OBJS) 可以打印 4 .o.
那么根本原因是什么?
最佳答案
作为make
读取 makefile
, 它用当前值 ${OBJS}
扩展规则行的 RHS* (${TARGET}: ${OBJS}
等行中的 ${OBJS}
) .当在命令中使用宏时,它会在命令执行时展开,因此 echo ${OBJS}
从文件末尾获取值,因为在读取整个文件之前它不会展开。
此行为是为 POSIX 指定的 make
在关于“宏”的部分:
Macros
…
Macros can appear anywhere in the makefile. Macro expansions using the forms
$(string1)
or${string1}
shall be replaced bystring2
, as follows:
Macros in target lines shall be evaluated when the target line is read.
Macros in
makefile
command lines shall be evaluated when the command is executed.Macros in the string before the
<equals-sign>
in a macro definition shall be evaluated when the macro assignment is made.Macros after the
<equals-sign>
in a macro definition shall not be evaluated until the defined macro is used in a rule or command, or before the<equals-sign>
in a macro definition.
第一个项目符号定义了我陈述的行为。
规范前面有一条有趣的评论(在“Makefile 语法”下)
Macros can also be defined more than once, and the value of the macro is specified in Macros.
* RHS = 右侧
关于c++ - 为什么在makefile的末尾用+=不行,而在开头就可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21298802/