c++ - 为什么在makefile的末尾用+=不行,而在开头就可以?

标签 c++ makefile

enter image description here

我在 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 by string2, 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/

相关文章:

c++ - undefined reference 错误 Makefile c++

c++ - xmath.h 是做什么用的?

c++ - 无法使用 Cairo 在 Gtk drawing_area 上绘画

linux - 是否有人有补丁或 kludge 技巧,以便我能够使用 gnutls-2.12.5 交叉编译 climm-0.6.4?

c++ - 使用 USERNAME :PASSWORD but not for SERIAL:TOKEN? 进行字符串化

path - 如何影响Makefile变量中的PATH?为什么我的示例不起作用?

C++ 使用 makefile 链接到库(newbe)

c++ - 如何在 C++ 中同时拥有 32 位和 64 位 float

javascript - 从 C/C++ 移植到 JavaScript 时如何处理负数或无符号字符?

c++ - 在访问冲突时创建转储文件