Make computes wildcard too early?
I have a make file of, more or less, the following structure that compiles C++ source code:
.PHONY: all
all: compile_obj_files my_binary
# This rule generates the object files. It works fine afaik.
.PHONY: compile_obj_files
compile_obj_files:
$(MAKE) --file=child.makefile
# my_binary is a real binary 开发者_JAVA技巧file that I wish to build.
my_binary: $(wildcard *.o)
$(CC) $(wildcard *.o) -o my_binary
On the first run this make file generated all the object files but $(wildcard *.o)
returned an empty list. On the second run it compiled nothing, as expected, and $(wildcard *.o)
indeed returned all the object files. It looks like $(wildcard *.o)
is executed before all the object files are created, despite the fact that my_binary
rule runs always after compile_obj_files
. I sit looking helpless on this script without any idea what is wrong here (must be something silly). Can you think of anything?
You should really not use $(wildcard ...)
inside rules, but rather do something like
MYSRC:=$(wildcard *.c)
MYOBJ:=$(patsubst %.c, %.o, $(MYSRC))
%.o: %.c
$(CC) -c $< -o $@
my_binary: $(MYOBJ)
$(CC) $^ -o $@
This way you know that MYSRC
and MYOBJ
match. Also note the use of $<
to denote the dependency of the current target and $@
to denote the target filename of the current target.
EDIT: Changed $<
to $^
in the link step to include all object files, not just the last one.
EDIT: If you don't want to extract the source filenames from child.makefile
, you should be able to do something like this:
.PHONY: all
all:
$(MAKE) --file=child.makefile
$(MAKE) my_binary OBJS="$(wildcard *.o)"
my_binary: $(OBJS)
$(CC) $< -o my_binary
The important part is that the value of OBJS
is consistent when building my_binary
. This way, you clearly split the build into two steps, and the list of object files is read before executing the second make.
精彩评论