2009年12月28日星期一

Makefile

Makefile is simple but very useful, some programmer will ignore the importance, epecially for those embedded programmer. I would like to illusate some basic but very good rule in Makefile.

Makefile Goal
- only compile the source if it is updated, should not touch any other source and object file, generate the output (executable)

how to reach this goal?
1. define a marco for the source file
SRC=a.c b.c c.c d.c
2. generate a marco for the object file
OBJ=$(SRC:.c=.o)
#this will replace .c with .o , i.e. OBJ now equal to
#a.o b.o c.o d.o
3. setup a depency between target and object file
TAR=output
$(TAR):$(OBJ)
gcc -o $(TAR) $(OBJ)


4.setup a depenency between object file and source file
$(OBJ):%.o:%.c
gcc -c -o $@ $<

5.clean
clean:
rm -f $(TAR) $(OBJ)


There is only a little beauty of Makefile, there is a lot of advance feature...

2 則留言:

  1. I guess one of the major barrier for learning Makefile is to understand the meaning of some symbols like: "$@ $<". There is no way you can tell what does that means unless RTFM or STFW.
    In addition, another good thing for the Makefile is you can embedd some script commands(echo, awk etc) and simple logic(if, else) to make it even more powerful

    回覆刪除
  2. this $@, $< is special marco which means the target and the dependency in the dependency rule,
    in our case, %.o is the target and %.c is the dependency,

    Ya, awk is also helpful..but I always forget the syntax..=_=

    回覆刪除