利用caffe自带的Makefile编译自定义so文件

时间:2023-03-09 20:18:40
利用caffe自带的Makefile编译自定义so文件

1、文件目录结构

caffe-root

  |--include

  |--example

  |--modules

        |--test.h

        |--test.cpp

  |--python

  |--src

  |--tools

modules为我们添加的目录和文件

2、修改Makefile文件

(1)添加生成动态链接库文件名称

DYNAMIC_NAME_MODULES:=$(LIB_BUILD_DIR)/libmodules.so

(2)获取所有源文件

# CXX_SRCS are the source files excluding the test ones.
CXX_SRCS := $(shell find src/$(PROJECT) ! -name "test_*.cpp" -name "*.cpp")
# CU_SRCS are the cuda source files
CU_SRCS := $(shell find src/$(PROJECT) ! -name "test_*.cu" -name "*.cu")
# MODULES_SRCS are the source files excluding the test ones.
MODULES_SRCS := $(shell find modules ! -name "test_*.cpp" -name "*.cpp")

(3)设置源文件对应的目标文件

# The objects corresponding to the source files
# These objects will be linked into the final shared library, so we
# exclude the tool, example, and test objects.
CXX_OBJS := $(addprefix $(BUILD_DIR)/, ${CXX_SRCS:.cpp=.o})
CU_OBJS := $(addprefix $(BUILD_DIR)/cuda/, ${CU_SRCS:.cu=.o})
MODULES_OBJS := $(addprefix $(BUILD_DIR)/, ${MODULES_SRCS:.cpp=.o})

(4)生成链接库命令

$(DYNAMIC_NAME_MODULES): $(MODULES_OBJS) $(DYNAMIC_NAME) | $(LIB_BUILD_DIR)
@ echo LD -o $@
$(Q)$(CXX) -shared -o $@ $(MODULES_OBJS) $(LINKFLAGS) $(LDFLAGS) -l$(LIBRARY_NAME) -Wl,-rpath,$(ORIGIN)/./lib

注意:$(DYNAMIC_NAME) 为 caffe.so,因为modules中的文件用到了caffe中的函数,如果为用到则可以去掉该变量

(5)添加到targets

lib: $(STATIC_NAME) $(DYNAMIC_NAME) $(DYNAMIC_NAME_MODULES)

3、$ cd CAFFE_ROOT

$ make -j

生成的链接库位于 CAFFE_ROOT/build/lib 中