Just to see if it was possible on my current project, I tried to generate C++ code files from their .proto definitions whenever CMake ran. To do this, I added a few lines to the CMakeLists.txt file of the project. The idea is to use execute_process to call protoc and generate the files in the appropriate folder in the solution.
First, file(GLOB …) is used to set all of the .proto files into an iterable variable. Then, variables are setup for the proto_path and cpp_out variables.
After that, the files variable is looped and for each of the files we use execute_process to invoke protoc and generate the .pb.h and .pb.cc files.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
file(GLOB PROTOBUF_DEFINITION_FILES "*.proto") | |
set(PROTOBUF_INPUT_DIRECTORY "${PROJECT_SOURCE_DIR}") | |
set(PROTOBUF_OUTPUT_DIRECTORY "${PROJECT_SOURCE_DIR}/Models/Proto/") | |
foreach(file ${PROTOBUF_DEFINITION_FILES}) | |
set(PROTOBUF_ARGUMENTS "protoc –proto_path=\"${PROTOBUF_INPUT_DIRECTORY}\" –cpp_out=\"${PROTOBUF_OUTPUT_DIRECTORY}\" \"${file}\"") | |
execute_process(COMMAND ${PROTOBUF_OUTPUT_DIRECTORY} | |
WORKING_DIRECTORY ${PROJECT_SOURCE_DIR} | |
RESULT_VARIABLE PROTOBUF_RESULT | |
OUTPUT_VARIABLE PROTOBUF_OUTPUT_VARIABLE) | |
endforeach() | |
file(GLOB PROTOBUF_MODELS_INCLUDES "Models/Proto/*.pb.cc" "Models/Proto/*.hpp") |
Finally, we want to add the .pb.h and .pb.cc files to a variable for the final build. To do so, use file(GLOB …) again to search for all appropriate files.