I am learning to write makefile recently. All the documents I am reading tell me that I have to write a rule to execute commands. But I found that the following Makefile could generate object files with out any compile command. Why?
SOURCES=$(wildcard src/*.c)
OBJECTS=$(patsubst %.c, %.o, $(SOURCES))
all: $(OBJECTS)
When I type make in terminal, I get this:
cc -c -o xxx.o xxx.c
How does it happened?
The simple answer is that %.o is a target that matches any file ending in .o. "%.o: %. c" means that any file ending in .o depends on the same filename ending in . c to be present.
The Cleanup Rule clean: rm *.o prog3 This is an optional rule. It allows you to type 'make clean' at the command line to get rid of your object and executable files. Sometimes the compiler will link or compile files incorrectly and the only way to get a fresh start is to remove all the object and executable files.
The order of rules is not significant, except for determining the default goal: the target for make to consider, if you do not otherwise specify one. The default goal is the target of the first rule in the first makefile. If the first rule has multiple targets, only the first target is taken as the default.
The $@ and $< are called automatic variables. The variable $@ represents the name of the target and $< represents the first prerequisite required to create the output file. For example: hello.o: hello.c hello.h gcc -c $< -o $@ Here, hello.o is the output file.
Why does makefile automatically generate object file(*.o) without any specific rule?
Because it has a set of Built-in rules.
Make uses implicit rules like the following:
%.o: %.c
$(CC) $(CPPFLAGS) $(CFLAGS) -c
%: %.o
$(CC) $(LDFLAGS) n.o $(LOADLIBES) $(LDLIBS)
You can see all of them with make -p
. While make -d
shows the applied rules.
As Ian Abbott pointed out in the comment:
make -p
needs to be run from a directory that has no makefile (and no Makefile, and no GNUmakefile).
See also the relevant GNU make documentation
and this post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With