递归编译的Makefile的实现

最近写了一个递归Makefile,目的是既可以实现子模块的单独编译,也可以不做任何修改就和整个程序的整体进行无缝衔接的编译。具体的思路是借助第三方文件,将子模块编译好的.o文件的路径自动写到config.mk文件中,在总控Makfile中只需要include这个config.mk就可以。单个模块的编译只需要cd到相应目录就可以进行本模块的单独编译,整个程序的编译也只需要cd到顶层目录,分别执行make config,make,make install就可以进行编译和安装。下面这个就是顶层Makefile

CROSS_COMPILE=                                                                                            
#CC=/opt/arm-cross-compile/arm-2010.09/bin/arm-none-linux-gnueabi-gcc
#CC=gcc
CC=arm-linux-gnueabi-gcc
D=-DDEBUG
CFLAGS= -g -O3 $(D)

export CC CFLAGS 

INCLUDE_DIR = $(shell cd ./common/include/; pwd)
SUB_DIR= ./entry/	\
         ./sqlite/	\

NFS_DIR:=~/nfs
CORE_NAME = core
$(shell touch config.mk)
include ./config.mk 

all:$(OBJS)
	$(CC) $(CFLAGS) $^ -lpthread -L/home/jiang/nfs/usr/lib/ -lsqlite3 -o $(CORE_NAME)

config:
	@echo "OBJS+=\\" > config.mk	
	@for dir in $(SUB_DIR);         \
	do                              \
		echo "\n";  		\
		$(MAKE) -C $$dir ;      \
		echo "\n";              \
	done

clean:
	$(RM) ./config.mk 		
	@for dir in $(SUB_DIR);         \
	do                              \
		echo "\n";              \
		$(MAKE) -C $$dir clean; \
		echo "\n";              \
		done
install:
	cp $(CORE_NAME) $(NFS_DIR)

下面这个就是每一个子模块的Makfile,会把编译成功的.o文件路径添加到config.mk中

CUR_DIR=$(shell pwd)
OBJ_DIR:=$(CUR_DIR)/obj
INCLUDE_DIR= -I ./include -I ../common/include
SRC=$(wildcard ./src/*.c)

all:$(SRC)
	$(CC) $(CFLAGS) $(INCLUDE_DIR) -c $^ 
	mv ./*.o $(OBJ_DIR)
	echo "${OBJ_DIR}/*.o \\" >> ../config.mk 
	echo "\033[44;37m $(notdir $(CUR_DIR)) done \033[0m"
clean:
	$(RM) $(OBJ_DIR)/* 

下面就是config.mk的内容,会在顶层目录中执行make config之后自动生成

OBJS+=\
/home/jiang/Documents/Documents/IntellStorage/A9_main/A9_core/entry/obj/*.o \
/home/jiang/Documents/Documents/IntellStorage/A9_main/A9_core/sqlite/obj/*.o \

为了使一个头文件的实例在整个工程中只有一份,对于接口文件,约定一律以inter_开头进行命名并且放置在自己的include目录中,下面这个脚本的作用就是扫描指定的子模块的include目录,将其中的inter_*头文件在entry模块的include中自动生成同名符号链接文件。

#|/bin/bash
#扫描指定include的文件,符合inter_*.h的文件会自动在entry/include中创建其符号链接

SHELL_DIR=$(cd $(dirname ${0});pwd)
cd ${SHELL_DIR}
SUB_INCLUDES="../camera/include ../buzzer/include ../gsm/include ../led/include ../sqlite/include ../zigbee/include"
for A_SUB_INCLUDE in ${SUB_INCLUDES}
do
	echo ${A_SUB_INCLUDE}
	(
	cd ${A_SUB_INCLUDE}
	HEADERS=$(ls ./inter*)
	for A_HEADER in ${HEADERS}
	do
		ln -s ../${A_SUB_INCLUDE}/${A_HEADER} ../../entry/include/${A_HEADER}
	done
	)
done
posted @ 2017-01-18 20:17  Abnor  阅读(1713)  评论(0编辑  收藏  举报