Search code examples
cmakeprotocol-buffersprotoc

How to substitute the extension for a cmake list of filenames


I am trying to build a c++ library from some protobuf definitions using cmake. I added a custom command to compile the proto to c++, but I have some issues with the output part. I need to specify which are the expected output files after protoc does its job. For this I would like to replace in my PROTO_SOURCEfile glob, the proto extension with .pb.cc and .pb.h

I basically need something like this, but for cmake.

I am building this command manually because I don't have protobuf cmake support available.

project(messages)

set(PROTO_PATH "${CMAKE_CURRENT_SOURCE_DIR}/proto_definitions")
file(GLOB PROTO_FILES "${PROTO_PATH}/*.proto")
#set(PROTO_SOURCES ???) # This needs to contain '*.pb.cc' and '*.pb.h'

add_custom_command(COMMAND protoc --cpp_out=${CMAKE_CURRENT_SOURCE_DIR}/compiled_proto ${PROTO_FILES}
               WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
               DEPENDS ${PROTO_FILES}
               OUTPUT ${PROTO_SOURCES})

add_library(${PROJECT_NAME} STATIC ${PROTO_SOURCES})

Solution

  • Use string(REGEX REPLACE) function:

    # Replace .proto -> .pb.cc
    string(REGEX REPLACE "[.]proto$" ".pb.cc" OUTPUT_SOURCES ${PROTO_FILES})
    # Replace .proto -> .pb.h
    string(REGEX REPLACE "[.]proto$" ".pb.h" OUTPUT_HEADERS ${PROTO_FILES})
    
    add_custom_command(COMMAND protoc <...>
       OUTPUT ${OUTPUT_SOURCES} ${OUTPUT_HEADERS})