0%

makefile根据文件目录来生成库

需求

根据src下目录名称来生成对应的库,不需要修改makefile,只需要添加文件夹从而生成新的库。

相关知识点:Makefile中嵌入一段shell脚本及函数列表

实现

SRC = $(shell find . -iname "*.c")
DIRS = $(shell ls -I include ./src)

.PHONY : clean install

all : objects libs

objects:$(SRC)
    @echo "making objects dir"
    @mkdir -p $(objects_dir)
    @echo "Generating new objects file...";
    @for f in $(SRC); do \
        OBJ=$(objects_dir)/`basename $$f|sed -e 's/\.c/\.o/'`; \
        echo "compiling \033[032m[$(CC)]\033[0m": $$f; \
        $(CC) $(CFLAGS) -c $$f -o $$OBJ; \
    done

libs:
    @echo "\nmaking libs ..."
    @for subdir in $(DIRS); do \
        target=$(addprefix lib, $(addsuffix .a, $$subdir)); \
        objs=`ls ./src/$$subdir|sed -e 's/\.c/\.o/'|sed -e 's#^#./$(objects_dir)/#'`; \
        $(AR) -rcs $$target $$objs; \
        echo "In subdir\033[32m" [$$subdir] "\033[0mGenerating new lib\033[31m": $$target"\033[0m"; \
    done

clean :
    @echo [Clean all]
    @rm -rf $(objects_dir)
    @rm -rf $(install_dir)
    @find -name "*.o" | xargs rm -rf
    @rm -rf *.a

install : *.a
    @echo "making install dir"
    @mkdir -p $(install_dir)
    @mv *.a $(install_dir)
    @cp include/*.h $(install_dir)
    @cp porting/*.h $(install_dir)

注意

addprefix

target=$(addprefix lib, $(addsuffix .a, $$subdir))

addprefix在shell脚本片段中,处理的文本为多个时会失败,具体原因未知…

shell变量与makefile变量

$(objects_dir)为shell变量,$$target为makefile变量

shell与``[反引号]

在for循环中,使用类似:

objs=$(shell ls ./src/$$subdir|sed -e 's/\.c/\.o/'|sed -e 's#^#./$(objects_dir)/#'); \ 

执行不成功:

/bin/sh: 3: ./output/objects/cmm: not found

修改为:

objs=`ls ./src/$$subdir|sed -e 's/\.c/\.o/'|sed -e 's#^#./$(objects_dir)/#'`; \