Linux Makefile多目录的编写

时间:2021-08-03 13:23:22

手头一个项目,需要编写项目的makefile

多目录结构:

csource/  

├── common
│   └── sqlite3
├── inc
│   ├── curl
│   ├── lua
│   └── Protection
├── lib
│   ├── arm
│   └── linux
├── obj
├── out
│   ├── arm
│   └── linux
├── src

源码目录src,输出目录out,include目录inc,输入链接库目录lib,常用静态函数和sqlite3目录common

makefile如下:

 

 1 PLAT= none
2 CC=
3 CXX=
4 CFLAGS=
5 LDFLAGS=
6 MKDIR_P=mkdir -p
7
8 PLATS= linux arm
9
10 root= libroot.so
11 root_a= libroot.a
12
13 INC_DIR= ./inc
14 COM_DIR= ./common
15 SQL_DIR= ./common/sqlite3
16 LUA_DIR= ./inc/lua
17 PRO_DIR= ./inc/Protection
18 INCLUDE= -I$(LUA_DIR) -I$(INC_DIR) -I$(COM_DIR) -I$(SQL_DIR) -I$(PRO_DIR)
19 DIR_SRC= ./src
20
21 SRC = $(wildcard ${DIR_SRC}/*.cpp)
22 OBJ = $(patsubst %.cpp,${DIR_OBJ}/%.o,$(notdir ${SRC})) $(DIR_OBJ)/sqlite3.o
23
24 SO_TARGET = ${DIR_BIN}/${root}
25 LIB_TARGET= ${DIR_BIN}/${root_a}
26
27
28 # Targets start here.
29 default: $(PLAT)
30
31 none:
32 @echo "Please do 'make PLATFORM' where PLATFORM is one of these:"
33 @echo " $(PLATS)"
34
35 ${SO_TARGET}:${OBJ}
36 $(CXX) $(OBJ) -o $@ $(LDFLAGS)
37 cp ${DIR_BIN}/${root} ./test/ -f
38
39 ${LIB_TARGET}:${OBJ}
40 $(AR) $@ ${OBJ}
41 $(RANLIB) $@
42
43 dir:
44 $(MKDIR_P) $(DIR_OBJ) $(DIR_BIN);
45
46 all:$(SO_TARGET) $(LIB_TARGET)
47
48 ALL = dir all
49
50 linux:
51 $(MAKE) $(ALL) DIR_OBJ="./obj_linux/" DIR_BIN="./out/linux" \
52 CC="gcc" CXX="g++" AR="ar rcu" RANLIB="ranlib" \
53 CFLAGS="-Wno-write-strings -m32 -O2 -D_DEBUG -D_LINUX -fPIC" \
54 LDFLAGS="-O2 -shared -m32 -ldl -pthread -lrt -L./lib/linux -llua -lProtection -lz -lcurl"
55
56 arm:
57 $(MAKE) $(ALL) DIR_OBJ="./obj_arm/" DIR_BIN="./out/arm" \
58 CC="arm-linux-gnueabihf-gcc" CXX="arm-linux-gnueabihf-g++" \
59 AR="arm-linux-gnueabihf-ar rcu" RANLIB="arm-linux-gnueabihf-ranlib" \
60 CFLAGS="-Wno-write-strings -O2 -D_ARM -D__LINUX -fPIC" \
61 LDFLAGS="-O2 -shared -ldl -pthread -lrt -L./lib/arm -llua -lProtection -lz -lcurl"
62
63
64 # list targets that do not create files (but not all makes understand .PHONY)
65 .PHONY: all $(PLATS) default clean none
66
67 ${DIR_OBJ}/%.o:${DIR_SRC}/%.cpp
68 $(CXX) $(CFLAGS) $(INCLUDE) -c $< -o $@
69
70 ${DIR_OBJ}/sqlite3.o:${DIR_SRC}/sqlite3.c
71 $(CC) $(CFLAGS) $(INCLUDE) -c $< -o $@
72
73 .PHONY:clean
74 clean:
75 -find ${DIR_OBJ} -name *.o -exec rm -rf {} \;