# Generate Protocol Buffers on build with CMake

https://jaredrhodes.com/blog/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](https://cmake.org/) ran. To do this, I added a few lines to the CMakeLists.txt file of the project. The idea is to use [execute\_process](https://cmake.org/cmake/help/latest/command/execute_process.html) to call [protoc](http://google.github.io/proto-lens/installing-protoc.html) 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](https://cmake.org/cmake/help/latest/command/execute_process.html) to invoke [protoc](http://google.github.io/proto-lens/installing-protoc.html) and generate the .pb.h and .pb.cc files.

https://gist.github.com/QiMata/7586d6e42b5efa62c2aed892d8410dd9

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.
