Saturday 7 November 2015

Makefile小记(malloc project)

What a Rule Looks Like

target … : prerequisitesrecipe

target is usually the name of a file that is generated by a program; examples of targets are executable or object files. A target can also be the name of an action to carry out, such as ‘clean’ (see Phony Targets).
prerequisite is a file that is used as input to create the target. A target often depends on several files.
recipe is an action that make carries out.

target:目标文件
prerequites:前提条件,意思就是如果要执行目标文件下的recipe,prerequites的存在是必须条件。
recipe:即是shell的命令

Automatic Variables
These variables have values computed afresh for each rule that is executed, based on the target and prerequisites of the rule.In this example, you would use ‘$@’ for the object file name and ‘$<’ for the source file name.It’s very important that you recognize the limited scope in which automatic variable values are available: they only have values within the recipe. In particular, you cannot use them anywhere within the target list of a rule; they have no value there and will expand to the empty string. Also, they cannot be accessed directly within the prerequisite list of a rule.

ps:When it is time to execute recipes to update a target, they are executed by invoking a new sub-shell for each line of the recipe, unless the .ONESHELL special target is in effect (see Using One Shell) (In practice, make may take shortcuts that do not affect the results.)

//-------------------------------------------------------------------------------------------------------------------------------

接下来我修改了Makefile,使得它能通过编译main.c成二进制文件到tests/main,通过./main输出结果:

  1 CC=gcc
  2 CFLAGS =-std=c99 -pedantic -Wextra -Wall -Werror
  3 LDFLAGS=-shared -fPIC
  4 TARGET=libmalloc.so
  5 CHECK=check
  6 
  7 SRC= ./src/metadata.c  ./src/malloc.c \
  8       ./src/calloc.c
  9 OBJ=$(SRC=.c:.o)
告诉makefile把.c文件转为.o

 10 RM = rm -fr
 11 
 12 
 13 #target $@, object $^, first dependency file $<
 14 $(TARGET):$(OBJ)
 15   $(CC) $(LDFLAGS) -o $@ $(SRC)
编译libmalloc.so,首先所有的.o文件要存在

 16 
 17 main:
 18   #$(MAKE) -C test (意思:如果有子makefile在test文件夹里,命令一起执行)
 19   $(CC) $(CFLAGS) -o tests/main src/main.c 
单独编译main函数

 20 
 21 check:all
 22 all:$(TARGET) $(OBJ) main

 23   LD_PRELOAD=./libmalloc.so ./tests/main
LD_PRELOAD是把自己的库替换系统提供的库,使得文件用的是我自己同名的malloc

 24 .PHONY: clean
 25 clean:
 26   $(RM) $(OBJ) $(TARGET) \

 27   $(RM) a.out tests/main





http://blog.csdn.net/liang13664759/article/details/1771246
Makefile 全面讲解

http://ccckmit.wikidot.com/code:c0p
build parse tree实例

GNU make: Secondary Expansion

make rules 和 implicit rule search 


No comments:

Post a Comment