如何在Makefile中以DEPENDS = $(OBJ _ $(dir))连接

时间:2014-02-10 17:06:17

标签: c makefile

我正在为使用多个dirs的build编写一个makefile。在我的makefile中,我有这个

1:dir=arch
2:CLEAN_FILES+=$(dir)/*.o
3:include $(dir)/Rules.mk
4:DEPENDS +=$(OBJS_arch)

arch中的Rules.mk创建一个名为$(OBJS_arch)的变量。这个逻辑适用于所有的拱形对象。

我希望用$(OBJS _ $(dir))替换第4行(硬编码)

2 个答案:

答案 0 :(得分:0)

选中制作join功能,

你可以尝试做,

DEPENDS=$(join OBJ_, $(dir))

制作手册说,

$(join list1,list2)

Concatenates the two arguments word by word: the two first words (one from each 
argument) concatenated form the first word of the result, the two second words 
form the second word of the result, and so on. So the nth word of the result 
comes from the nth word of each argument. If one argument has more words that the 
other, the extra words are copied unchanged into the result.

For example, ‘$(join a b,.c .o)’ produces ‘a.c b.o’. 

答案 1 :(得分:0)

哦,我想我终于明白了你遇到的问题。如果您显示不正确的行为并描述为什么它不是您想要的那样,那将非常有用。

反正。问题是你正在使用递归变量DEPENDS。在实际使用变量之前,递归变量的右侧不会扩展。所以当你写:

dir=one
CLEAN_FILES+=$(dir)/*.o
include $(dir)/Rules.mk
DEPENDS +=$(OBJS_$(dir))

dir=two
CLEAN_FILES+=$(dir)/*.o
include $(dir)/Rules.mk
DEPENDS +=$(OBJS_$(dir))

在此依赖之后将具有此字面值:$(OBJS_$(dir)) $(OBJS_$(dir))。该值不会在以后扩展。展开后,dir将是最后一个值,并且您将获得同一变量的多个副本。

您需要使用简单扩展的变量,而不是递归变量。要通过追加来执行此操作,首先将变量初始化为简单,然后追加将保持:

# Make sure DEPENDS is simply expanded
DEPENDS :=

dir=one
CLEAN_FILES+=$(dir)/*.o
include $(dir)/Rules.mk
DEPENDS +=$(OBJS_$(dir))

dir=two
CLEAN_FILES+=$(dir)/*.o
include $(dir)/Rules.mk
DEPENDS +=$(OBJS_$(dir))

这将做你想要的。

要在循环中执行此操作,因为这是makefile命令而不是shell命令,所以您必须使用eval,这绝对是高级用法。

这样的事情可以做到:

DIRS = one two three four

# Make sure DEPENDS is simply expanded
DEPENDS :=

# Define a user-defined macro to include Rules.mk and set DEPENDS
define ADD_DEPENDS
CLEAN_FILES += $1/*.o
include $1/Rules.mk
DEPENDS += $$(OBJS_$1)
endef

# Run it!
$(foreach D,$(DIRS),$(eval $(call ADD_DEPENDS,$D)))