库目录的Makefile(这里显示的是foo目录下的Makefile,其它者修改库名称及代码文件名称即可)
# A simple Makefile for lib(libxxx.a)
# By Late Lee(http://www.latelee.org)
AR = ar
ARFLAGS = cr
LIB = libfoo.a
RM = -rm -rf
OBJS := foo.o common.o
all: $(LIB)
$(LIB): $(OBJS)
$(AR) $(ARFLAGS) $@ $(OBJS)
clean:
$(RM) $(OBJS) $(LIB) *.bak *~
.PHONY: all clean
顶层目录的Makefile文件
#################################################################
# A simple Makefile
# By Late Lee(http://www.latelee.org)
#
# bugs:
# 1. 需要显式指定库位置、名称;
# 2. make 及 make clean处理得不好(对于库,要么删除再编译,要么无操作);
#################################################################
CC=gcc
CFLAGS = -Wall
DEBUG = y
ifeq ( $(DEBUG), y)
CFLAGS += -g
else
CFLAGS += -O2
endif
SUBDIRS := foo bar bt
LIBS := bt/libbt.a foo/libfoo.a bar/libbar.a
LDFLAGS = $(LIBS)
RM = -rm -rf
__OBJS = main.o
__OBJS += example.o
__SRCS = $(subst .o,.c, $(__OBJS))
target = a.out
MAKE = make
#all: clean $(target)
all: $(target)
$(__OBJS): $(__SRCS)
$(CC) $(CFLAGS) -c $^ -I ./configs/
$(target): $(__OBJS)
for dir in $(SUBDIRS); \
do $(MAKE) -C $ $dir all || exit 1; \
done
$(CC) $(CFLAGS) $^ -o $@ $(LDFLAGS)
clean:
@for dir in $(SUBDIRS); do make -C $ $dir clean|| exit 1; done
$(RM) $(__OBJS) $(target) *.bak *~
.PHONY: all clean
执行make的过程:
[latelee@latelee lib-test] $ make
gcc -Wall -g -c main.c example.c -I . /configs/
example.c: In function ‘fun’:
example.c:10: warning: unused variable ‘buf’
for dir in foo bar bt ; \
do make -C $dir all || exit 1 ; \
done
make [1]: Entering directory ` /home/latelee/linux-c/lib-test/foo'
cc -c -o foo.o foo.c
cc -c -o common.o common.c
ar cr libfoo.a foo.o common.o
make [1]: Leaving directory ` /home/latelee/linux-c/lib-test/foo'
make [1]: Entering directory ` /home/latelee/linux-c/lib-test/bar'
cc -c -o bar.o bar.c
cc -c -o common.o common.c
ar cr libbar.a bar.o common.o
make [1]: Leaving directory ` /home/latelee/linux-c/lib-test/bar'
make [1]: Entering directory ` /home/latelee/linux-c/lib-test/bt'
cc -c -o backtrace.o backtrace.c
ar cr libbt.a backtrace.o
make [1]: Leaving directory ` /home/latelee/linux-c/lib-test/bt'
gcc -Wall -g main.o example.o -o a.out bt /libbt.a foo/libfoo.a bar/libbar.a