Skip to content

Instantly share code, notes, and snippets.

@zeroxia
Last active May 10, 2022 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeroxia/47c02cc8559947e7dc109117a4e41102 to your computer and use it in GitHub Desktop.
Save zeroxia/47c02cc8559947e7dc109117a4e41102 to your computer and use it in GitHub Desktop.
Protobuf from *.proto to *.pb.cc and *.pb.h and library
####
#### NOTE: This is not verified.
####
cmake_minimum_required(VERSION 3.12)
project(proto_lib)
#set(CMAKE_CURRENT_BINARY_DIR ${CMAKE_BINARY_DIR})
set(PROTO_ROOT_DIR ${CMAKE_SOURCE_DIR})
file(GLOB PROTO_LIST_1 ${PROTO_ROOT_DIR}/path/to/one/*.proto)
file(GLOB PROTO_LIST_2 ${PROTO_ROOT_DIR}/path/to/two/*.proto)
## https://cmake.org/cmake/help/v3.16/module/FindProtobuf.html
## Use build-in CMake module: FindProtobuf to do C++ sources generation.
## This avoids re-building the "common_proto" library everytime you make changes to CMakeLists.txt.
find_package(Protobuf REQUIRED)
message(STATUS "Protobuf: ${Protobuf_VERSION}, libs: ${Protobuf_LIBRARIES}")
set(Protobuf_IMPORT_DIRS ${PROTO_ROOT_DIR})
## Non-intuitive option to keep directory structure.
## https://gitlab.kitware.com/cmake/cmake/-/issues/19968
## https://groups.google.com/g/protobuf/c/eow2fNDUHvc/m/hTtlortuCgAJ
set(PROTOBUF_GENERATE_CPP_APPEND_PATH OFF)
protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS ${PROTO_LIST_1} ${PROTO_LIST_2})
add_library(${PROJECT_NAME} STATIC ${PROTO_SRCS} ${PROTO_HDRS})
target_include_directories(${PROJECT_NAME} PUBLIC ${CMAKE_BINARY_DIR})
set_property(TARGET ${PROJECT_NAME} PROPERTY POSITION_INDEPENDENT_CODE ON)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment