makefile疑问

工作需要最近在看make
在GNU make官方文档上有个例子没太看明白,有懂的朋友希望给与解答;
如下Makefile:

objects = main.o kbd.o command.o display.o \
          insert.o search.o files.o utils.o

edit : $(objects)
        cc -o edit $(objects)
main.o : main.c defs.h
        cc -c main.c
kbd.o : kbd.c defs.h command.h
        cc -c kbd.c
command.o : command.c defs.h command.h
        cc -c command.c
display.o : display.c defs.h buffer.h
        cc -c display.c
insert.o : insert.c defs.h buffer.h
        cc -c insert.c
search.o : search.c defs.h buffer.h
        cc -c search.c
files.o : files.c defs.h buffer.h command.h
        cc -c files.c
utils.o : utils.c defs.h
        cc -c utils.c
clean :
        rm edit $(objects)
        

在下一小节被修改为如下:

objects = main.o kbd.o command.o display.o \
          insert.o search.o files.o utils.o

edit : $(objects)
        cc -o edit $(objects)

main.o : defs.h
kbd.o : defs.h command.h
command.o : defs.h command.h
display.o : defs.h buffer.h
insert.o : defs.h buffer.h
search.o : defs.h buffer.h
files.o : defs.h buffer.h command.h
utils.o : defs.h

.PHONY : clean
clean :
        rm edit $(objects)

看官方的文档说有隐含规则?excuse me ?
官方manual如下:

It is not necessary to spell out the recipes for compiling the individual C source files, because make can figure them out: it has an implicit rule for updating a ‘.o’ file from a correspondingly named ‘.c’ file using a ‘cc -c’ command. For example, it will use the recipe ‘cc -c main.c -o main.o’ to compile main.c into main.o. We can therefore omit the recipes from the rules for the object files. See Using Implicit Rules.When a ‘.c’ file is used automatically in this way, it is also automatically added to the list of prerequisites. We can therefore omit the ‘.c’ files from the prerequisites, provided we omit the recipe.
阅读 2.2k
1 个回答

若某个对象文件 x.o 被依赖,像这样

build: x.o
    ...

x.o 没有被定义时,Makefile 自动扩展成这样

build: x.o
    ...
    
x.o: x.c
    cc -o x.o x.c

x.o 被定义了,但是没有包含 x.c 依赖项时,x.c 被自动加入,即

build: x.o
    ...
    
x.o: a.c

将被自动扩展为

build: x.o
    ...
    
x.o: a.c x.c

edit: $(objects)
    cc -o edit $(objects)

可简写成

edit: $(objects)
    cc -o $@ $^

其中 $@ 代表编译目标 edit$^ 代表依赖项 $(objects)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进