5

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?

ParrRen
  • 63
  • 5

1 Answers1

10

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 -dshows 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.

Community
  • 1
  • 1
terence hill
  • 3,354
  • 18
  • 31