dream/ 3月 29, 2018/ C/C++/ 0评论

本文包括项目makefile模板、动态库和静态库makefile模板。

文件结构

.
├── bin
│   └── test.out
├── include
│   └── reply.h
├── lib
│   ├── libreply.a
│   ├── libreply.so
│   ├── makefile_a
│   ├── makefile_so
│   └── reply.cpp
├── makefile

└── test.cpp

注:编译库时应根据需要将makefile_a或makefile_so重命名为makefile

 

1.整体项目makefile

SRCS    = $(wildcard *.cpp)
OBJS    = $(patsubst %.cpp, %.o, $(SRCS))
 
CC      = g++
CFLAGS  = -g -Wall -O0
 
TARGET      = ./bin/test.out
INC_PATH    = -I$(TOP_DIR)./include/
LIB_PATH    = -L$(TOP_DIR)./lib/
 
EXT_LIB     = #./lib/libreply.a					#如果需要使用静态库时修改的参数
EXT_SO		= -L. -lreply -Wl,--rpath=./lib/	#如果需要使用动态库时修改的参数
 
all:$(TARGET)
 
$(TARGET):$(OBJS)
    $(CC) $(LIB_PATH) $(CFLAGS) -o $@ $^ $(EXT_LIB) $(EXT_SO) 
 
%.o:%.cpp
    $(CC) $(INC_PATH) $(CFLAGS) -c -o $@ $<
%.o:%.c
    $(CC) $(INC_PATH) $(CFLAGS) -c -o $@ $<
 
run:$(TARGET)
    $(TARGET)
 
clear:
    rm -rf $(OBJS)
 
.PHONY:clean
clean:
    rm -rf $(TARGET) $(OBJS)

2.静态库makefile_a

SRCS    = $(wildcard *.cpp)
OBJS    = $(patsubst %.cpp, %.o, $(SRCS))
 
CC      = g++
CFLAGS  = -g -Wall -O0
 
TARGET      = libreply.a
INC_PATH    = -I$(TOP_DIR)..
LIB_PATH    = -L$(TOP_DIR)..
 
EXT_LIB     = #../lib/libreply.a
EXT_SO		= #-L. -lreply -Wl,--rpath=./lib/
EXT_SO_CC	= #-fPIC
 
all:$(TARGET)
 
$(TARGET):$(OBJS)
    ar crv $@ $^
#$(CC) $(LIB_PATH) $(CFLAGS) -o $@ $^ $(EXT_LIB) $(EXT_SO) 
 
%.o:%.cpp
    $(CC) $(INC_PATH) $(CFLAGS) -c -o $@ $<
%.o:%.c
    $(CC) $(INC_PATH) $(CFLAGS) -c -o $@ $<
 
run:$(TARGET)
    $(TARGET)
 
clear:	#只删除中间文件的命令
    rm -rf $(OBJS)
    
.PHONY:clean
clean:
    rm -rf $(TARGET) $(OBJS)

3.动态库makefile_so

SRCS    = $(wildcard *.cpp)
OBJS    = $(patsubst %.cpp, %.o, $(SRCS))
 
CC      = g++
CFLAGS  = -g -Wall -O0 $(EXT_SO_CC)
 
TARGET      = libreply.so
INC_PATH    = -I$(TOP_DIR)..
LIB_PATH    = -L$(TOP_DIR)..
 
EXT_LIB     = #../lib/libreply.a
EXT_SO		= -L. -lreply -Wl,--rpath=./lib/
EXT_SO_CC	= -fPIC	#编译动态库时需要额外添加的参数
 
all:$(TARGET)
 
$(TARGET):$(OBJS)
    $(CC) -shared -fPIC -o $(TARGET) $(OBJS)  
 
%.o:%.cpp
    $(CC) $(INC_PATH) $(CFLAGS) -c -o $@ $<
%.o:%.c
    $(CC) $(INC_PATH) $(CFLAGS) -c -o $@ $<
 
run:$(TARGET)
    $(TARGET)
 
clear:	#只删除中间文件的命令
    rm -rf $(OBJS)
    
.PHONY:clean
clean:
    rm -rf $(TARGET) $(OBJS)

 

点击数:91

Share this Post

说点什么

avatar
300
  订阅  
提醒