多目录Makefile写法

库目录的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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值