一个cmakelist的例子(自动处理多个proto)
背景:
由于项目需要,把所有的proto文件放在了统一的文件夹中,为了方便更新以及加快编译速度,要把这个proto自动转成.cc .pb.h文件,再编译成so。
为此,写了个cmakelist.txt。
主要功能:
1)自动遍历指定目录下所有proto文件,调用ptotoc生成.cc文件,如下图:cc文件存放在上一级目录,目录结构类似。
2)编译成so。
目录结构:
其中common、geometry等文件夹里面放的都是.proto
上代码CMakeLists.txt:
cmake_minimum_required(VERSION 3.12) set(CMAKE_FIND_PACKAGE_PREFER_CONFIG ON) project(dros_proto) set(dp_MAJOR_VERSION 0) set(dp_MINOR_VERSION 2) set(dp_PATCH_VERSION 0) set(dp_VERSION "${dp_MAJOR_VERSION}.${dp_MINOR_VERSION}.${dp_PATCH_VERSION}") set(CMAKE_CXX_STANDARD 14) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../lib) file(GLOB protobuf_files ${CMAKE_CURRENT_SOURCE_DIR}/common/*.proto ${CMAKE_CURRENT_SOURCE_DIR}/geometry/*.proto ${CMAKE_CURRENT_SOURCE_DIR}/navigation/*.proto ${CMAKE_CURRENT_SOURCE_DIR}/sensor/*.proto ${CMAKE_CURRENT_SOURCE_DIR}/tutorials/*.proto ) set(3rd_DIR "${PROJECT_SOURCE_DIR}/../../thirdparty") set(Protobuf_DIR "${3rd_DIR}/protobuf3.14.0.0") set(PROTO_META_BASE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../proto_cpp) list(APPEND PROTO_FLAGS -I${CMAKE_CURRENT_SOURCE_DIR}/ -I${Protobuf_DIR}/src/) if(${CMAKE_SYSTEM_PROCESSOR} MATCHES "x86_64") set(ARCH_TYPE x64) elseif(${CMAKE_SYSTEM_PROCESSOR} MATCHES "aarch64") set(ARCH_TYPE arm64) endif() message("arch type: ${CMAKE_SYSTEM_PROCESSOR}") set(PROTOC_EXE ${Protobuf_DIR}/bin/${ARCH_TYPE}/protoc-3.14.0.0) message("proto_exe = ${PROTOC_EXE}") foreach(FIL ${protobuf_files}) get_filename_component(FIL_WE ${FIL} NAME_WE) string(REGEX REPLACE ".+/(.+)\\..*" "\\1" FILE_NAME ${FIL}) string(REGEX REPLACE "(.+)\\${FILE_NAME}.*" "\\1" FILE_PATH ${FIL}) string(REGEX MATCH "(/proto/.*)" MATCH_PATH ${FILE_PATH}) # message("DDD: ${FILE_PATH}: ${MATCH_PATH}") string(REPLACE "/proto/" "/" OUT_PATH ${MATCH_PATH}) # message("SRC_CPP: ${PROTO_META_BASE_DIR}:${OUT_PATH}:${FIL_WE}.pb.cc") set(PROTO_SRCS "${PROTO_SRCS};${PROTO_META_BASE_DIR}${OUT_PATH}${FIL_WE}.pb.cc") set(PROTO_HDRS "${PROTO_HDRS};${PROTO_META_BASE_DIR}${OUT_PATH}${FIL_WE}.pb.h") EXECUTE_PROCESS( COMMAND ${PROTOC_EXE} ${PROTO_FLAGS} --cpp_out=${PROTO_META_BASE_DIR} ${FIL} ) endforeach() include_directories(${Protobuf_DIR}/src) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../proto_cpp) add_library(${PROJECT_NAME} SHARED ${PROTO_SRCS} ${PROTO_HDRS} ) set_target_properties(${PROJECT_NAME} PROPERTIES VERSION ${dp_VERSION} SOVERSION ${dp_MAJOR_VERSION})