This document explains how to use the function `protobuf_generate` which is provided by protobuf's CMake module.
## Usage
In the same directory that called `find_package(protobuf CONFIG)` and any of its subdirectories, the CMake function `protobuf_generate` is made available by
[`protobuf-generate.cmake`](../cmake/protobuf-generate.cmake). It can be used to automatically generate source files from `.proto` schema files at build time.
### Basic example
Let us see how `protobuf_generate` can be used to generate and compile the source files of a proto schema whenever an object target called `proto-objects` is built.
Given the following directory structure:
-`proto/helloworld/helloworld.proto`
-`CMakeLists.txt`
where `helloworld.proto` is a protobuf schema file and `CMakeLists.txt` contains:
[build] [1/2] Running cpp protocol buffer compiler on /proto/helloworld/helloworld.proto
[build] [2/2] Building CXX object /build/generated/helloworld/helloworld.pb.cc.o
```
### gRPC example
`protobuf_generate` can also be customized to invoke plugins like gRPC's `grpc_cpp_plugin`. Given the same directory structure as in the [basic example](#basic-example)
And `protoc` will automatically be re-run whenever the schema files change and `proto-objects` is built.
### Note on unity builds
Since protobuf's generated source files are unsuited for [jumbo/unity builds](https://cmake.org/cmake/help/latest/prop_tgt/UNITY_BUILD.html) it is recommended
to exclude them from such builds which can be achieved by adjusting their properties:
For each source file ending in `proto` of the argument provided to `TARGET` or each file provided through `PROTOS`, `protobuf_generate` will set up
a [add_custom_command](https://cmake.org/cmake/help/latest/command/add_custom_command.html) which depends on `protobuf::protoc` and the proto files.
It declares the generated source files as `OUTPUT` which means that any target that depends on them will automatically cause the custom command to execute
when it is brought up to date. The command itself is made up of the arguments for `protoc`, like the output directory, the schema files, the language to
generate for, the plugins to use, etc.
## Reference
Arguments accepted by `protobuf_generate`.
Flag arguments:
-`APPEND_PATH` — A flag that causes the base path of all proto schema files to be added to `IMPORT_DIRS`.