1、目录结构如下:
[root@localhost libname]# tree . +-- include ¦ +-- headerA.h ¦ +-- headerB.h +-- lib +-- Makefile +-- src ¦ +-- cppsrcA.cpp ¦ +-- cppsrcB.cpp ¦ +-- csrcA.c ¦ +-- csrcB.c +-- test 4 directories, 7 files
2、Makefile内容为:
CC = gcc CXX = g++ AR = ar -r RM = rm -f #INSTALL = /usr/bin/install -m 644 #INSTALL_BIN = /usr/bin/install -m 755 # you can specify LIBTYPE=static when executing make, if you want to create a static library ifeq ($(LIBTYPE),static) CFLAGS = -I./include CXXFLAGS = -I./include else CFLAGS = -I./include -fPIC CXXFLAGS = -I./include -fPIC LDFLAGS = -fPIC -shared endif C_SRC = src/csrcA.c \ src/csrcB.c CXX_SRC = src/cppsrcA.cpp \ src/cppsrcB.cpp SRC_DIR = src STATIC_OBJ_DIR =lib_obj/static_obj DYNAMIC_OBJ_DIR=lib_obj/dynamic_obj LIB_DIR = lib STATIC_LIB = libname.a DYNAMIC_LIB = libname.so ifeq ($(LIBTYPE),static) LIB_NAME = $(STATIC_LIB) OBJS_DIR = $(STATIC_OBJ_DIR) else LIB_NAME = $(DYNAMIC_LIB) OBJS_DIR = $(DYNAMIC_OBJ_DIR) endif C_OBJS = $(patsubst $(SRC_DIR)/%.c, $(OBJS_DIR)/%.o, $(C_SRC)) CXX_OBJS = $(patsubst $(SRC_DIR)/%.cpp, $(OBJS_DIR)/%.o, $(CXX_SRC)) ALL_OBJS = $(C_OBJS) $(CXX_OBJS) INSTALL_PREFIX=/usr/local/libname all: $(LIB_NAME) $(STATIC_LIB): $(OBJS_DIR) $(ALL_OBJS) $(AR) $(LIB_DIR)/$@ $(ALL_OBJS) $(DYNAMIC_LIB): $(OBJS_DIR) $(ALL_OBJS) $(CC) $(LDFLAGS) $(ALL_OBJS) -o $(LIB_DIR)/$@ $(OBJS_DIR): @if [ ! -d $(OBJS_DIR) ]; then \ echo mkdir -p $(OBJS_DIR) ; \ mkdir -p $(OBJS_DIR); \ fi $(C_OBJS):$(OBJS_DIR)/%.o:$(SRC_DIR)/%.c $(CC) $(CFLAGS) -c $< -o $@ $(CXX_OBJS):$(OBJS_DIR)/%.o:$(SRC_DIR)/%.cpp $(CXX) $(CXXFLAGS) -c $< -o $@ #install: #uninstall: #test: .PHONY: cleanall clean cleanall: clean $(RM) $(LIB_DIR)/$(STATIC_LIB) $(LIB_DIR)/$(DYNAMIC_LIB) clean: $(RM) $(STATIC_OBJ_DIR)/*.o $(DYNAMIC_OBJ_DIR)/*.o
3、执行 make 和 make LIBTYPE=static 后的目录结构
[root@localhost libname]# tree . +-- include ¦ +-- headerA.h ¦ +-- headerB.h +-- lib ¦ +-- libname.a ¦ +-- libname.so +-- lib_obj ¦ +-- dynamic_obj ¦ ¦ +-- cppsrcA.o ¦ ¦ +-- cppsrcB.o ¦ ¦ +-- csrcA.o ¦ ¦ +-- csrcB.o ¦ +-- static_obj ¦ +-- cppsrcA.o ¦ +-- cppsrcB.o ¦ +-- csrcA.o ¦ +-- csrcB.o +-- Makefile +-- src ¦ +-- cppsrcA.cpp ¦ +-- cppsrcB.cpp ¦ +-- csrcA.c ¦ +-- csrcB.c +-- test 7 directories, 17 files