Build Tools CMake Libraries Protocol BUffers
Jared Rhodes  

Generate Protocol Buffers on build with CMake

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 files.

Finally, we want to add the .pb.h and files to a variable for the final build. To do so, use file(GLOB …) again to search for all appropriate files.


2 thoughts on “Generate Protocol Buffers on build with CMake

  1. themartylake

    Why not use the official find_package for Protobuf ?

    1. Jared Rhodes

      The code here should be more like the official package (as to not use things like file(GLOB) ). However, the official package seems to be limited to creating the pb.h and in the same folder as the .proto files which doesn’t work for our setup. We share the .proto files across multiple projects as a git submodule.

Leave A Comment