代码改变世界

Makefile 实例实践

2016-07-02 00:17  ljtcnblogs  阅读(296)  评论(0编辑  收藏  举报

本文为原创文章,转帖需指明该文链接

目录结构如下:

    comm/inc/apue.h

    comm/errorhandler.c

    atexit.c

    Makefile

文件内容如下:

    apue.h

  1 #ifndef __apue_h__
  2 #define __apue_h__

3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 #include <errno.h> //for definition of erron 7 #include <stdarg.h> //ISO C variable arguments 8 #define MAXLINE 4096 //max line length 9 void err_dump(const char *fmt, ...); 10 void err_msg(const char *fmt, ...);

 11 #endif

    errorhandler.c

  1 #include "apue.h"
  2 
  3 #define ERR_MESSAGE_NEED    1
  4 #define ERR_MESSAGE_NO      0
  5 
  6 static void err_doit(int errnoflag, int error, const char *fmt, va_list ap);
  7 
  8 //print a message, dupm core, and terminate
  9 void err_dump(const char *fmt, ...)
  10 {
  11     va_list ap;
  12     va_start(ap, fmt);
  13     err_doit(ERR_MESSAGE_NEED, errno, fmt, ap);
  14     va_end(ap);
  15     abort();
  16     exit(1);
  17 }

    atexit.c

  1 #include "apue.h"
  2 
  3 static void my_exit1(void);
  4 static void my_exit2(void);
  5 
  6 int main(void)
  7 {
  8     if(0 != atexit(my_exit2))
  9         err_sys("can't register my_exit2");
 10     if(0 != atexit(my_exit1))
 11         err_sys("can't register my_exit1");
 12     if(0 != atexit(my_exit1))
 13         err_sys("can't register my_exit1");
 14     printf("main is done\n");
 15     return 0;
 16 }

    Makefile

  1 CC       = gcc
  2 CFLAGS   = -Wall -O -g
  3 CXXFLAGS =
  4 INCLUDE  = -I ./comm/inc
  5 TARGET   = atexit
  6 #search paths for errorhandler.c,当存在多个路径时,可以使用 空格 或 : 来分割这些路径
  7 vpath %.c ./comm
  8 #下行是为依赖项 apue.h 准备的,比如 [errorhandler.o:errorhandler.c apue.h] 里的
  9 vpath %.h ./comm/inc
 10 
 11 OBJS     = errorhandler.o atexit.o
 12 all:$(OBJS)
 13    $(CC) $(CFLAGS) $(INCLUDE) -o $(TARGET) $^
 14    @echo ---target:$@
 15    @echo ---depend:$^
 16 #下行的 apue.h,可以不必写出来
 17 errorhandler.o:errorhandler.c apue.h
 18    $(CC) $(CFLAGS) $(INCLUDE) -c $^
 19    @echo ---target:$@
 20    @echo ---depend:$^
 21 atexit.o:atexit.c apue.h
 22    $(CC) $(CFLAGS) $(INCLUDE) -c $^
 23    @echo ---target:$@
 24    @echo ---depend:$^
 25 clean:
 26    rm -f *.o
 27    rm -f $(TARGET)

在 Makefile 里

    INCLUDE  = -I ./comm/inc 是为 gcc 编译文件时使用的

    vpath %.c ./comm  vpath %.h ./comm.inc 是为 make 程序使用

    @echo ---target:$@  是为了测试 $@ 是什么内容   @echo ---depend:$^ 是为了测试 $^ 是什么内容

Makefile 的自动变量

    $@  表示目标文件
    $^    表示所有的依赖文件
    $<    表示第一个依赖文件
    $?    表示比目标还要新的依赖文件列表