I have several projects that all depend on generated protobuf C++ files. The previous maintainer simply added the source to each target (causing the generated cpp files to be built multiple times). I thought I would save a little bit of time by building each protobuf cpp file once as a static library and linking them into each target as necessary.
Everything builds, but the target programs no longer function. I traced the error down to this code:
const google::protobuf::Descriptor *desc = google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName("my.type"); google::protobuf::Message *msg = google::protobuf::MessageFactory::generated_factory()->GetPrototype(desc)->New();
The FindMessageTypeByName() method call always returns nullptr when I link in the protobuf files as a static library. Doing a little reading, I found out that DescriptorPool::generated_pool() contains protocol messages built at compile time:
Generated protocol message classes which are compiled into the binary
will allocate their descriptors in this pool.
This raises several questions (answering any of them would be very educational):
- How does the protobuf library manage this registration? It feels like I would need to generate a function to run as a hook before main, or maybe a static list of initializer functions to call.
- Is there a way to statically link precompiled protobuf cpp files in a way that they are automatically added to the generated pool?
- If 2 is not possible, how would I add these precompiled proto files to a new pool?