Makefile 的一些使用

2017-05-20  本文已影响0人  printf_K

今天为了写编译原理的词法分析器,特地写了一下Makefile来简化编译过程,本来打算在子目录放置 Makefile 完成单独的编译,但是根目录里的Makefile不管怎么写都陷入死循环,所以现在我参照网上博客和一些大项目的Makefile 来编写这篇文章。可能不会一次写完,一点一点更新吧。

错误的写法

cd ./type
make
cd ..

一些多目录Makefile的写法

1.make -C

make -C 可以切换到指定目录执行make操作
比如:

make -C ./src

执行结果如下:

make -C ./src
make[1]: Entering directory '/home/k/temp/compiler_d/src'
......
....
....
make[1]: Leaving directory '/home/k/temp/compiler_d/src'

2.cd ${SUBDIR} && make

原文链接:[CSDN makefile进入子文件夹执行make][http://blog.csdn.net/taolinke/article/details/6626298]

SUBDIRS=directory1 directory2 directory3  
RECURSIVE_MAKE= @for subdir in $(SUBDIRS); \  
      do \  
      echo "making in $subdir"; \  
      ( cd $subdir && $(MAKE) all -f Makefile -e CC='${CC}' CFLAG='${CFLAG}') || exit 1; \  
       done  
RECURSIVE_CLEAN= @for subdir in $(SUBDIRS); \  
       do \  
       echo "cleaning in $subdir"; \  
       ( cd $subdir && $(MAKE) clean -f Makefile) || exit 1; \  
       done       
subdirs:  
        $(RECURSIVE_MAKE)       
all: subdirs    
dclean:  
            $(RECURSIVE_CLEAN)  

该思路是将cd 操作 与 make 操作 用&& 连接,在子shell中进行操作
通过几次实验后我才明白,在Makefile里的cd 命令 只是暂时更改了目录,用子shell的概念比较好理解这点
还有,Makefile里面${..}会在执行前提前替换,比如:

all:
        cd ./src && make && echo ${SUBSHELL}
        echo ${PWD}

输出为(home/k/temp/temp 为当前目录):

(cd ./src && make && echo "pwd" > temp && echo )
make[1]: Entering directory '/home/k/temp/temp/src'
gcc -o test main.c
make[1]: Leaving directory '/home/k/temp/temp/src'

echo /home/k/temp/temp
/home/k/temp/temp

其中 ${PWD} 被替换为当前路径,而 ${SUBSHELL} 由于没有定义,也不是环境变量,所以为空

上一篇 下一篇

猜你喜欢

热点阅读