Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does makefile automatically generate object file(*.o) without any specific rule?

Tags:

c

makefile

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?

like image 580
Hao Li Avatar asked Jan 18 '16 16:01

Hao Li


People also ask

What does o do in makefile?

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.

How do I clean my makefile?

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.

Does the order of files in a makefile matter?

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.

What is $@ $< in makefile?

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.


1 Answers

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.

like image 105
terence hill Avatar answered Sep 25 '22 20:09

terence hill