google / flatbuffers

FlatBuffers: Memory Efficient Serialization Library
https://flatbuffers.dev/
Apache License 2.0
22.52k stars 3.19k forks source link

Avoid ODR violations with flatbuffers::Verifier. #8274

Closed fergushenderson closed 3 months ago

fergushenderson commented 3 months ago

Fix "One Definition Rule" violation when using flatbuffers::Verifier with FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE defined in some compilation units and not defined in other compilation units.

The fix is to make Verifier a template class, with a boolean template parameter replacing the "#ifdef" conditionals; to rename it as VerifierTemplate; and then to use "#ifdef" only for a "using" declaration that defines the original name Verifier an an alias for the instantiated template. In this way, even if FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE is defined in some compilation units and not in others, as long as clients only reference flatbuffers::Verifier in .cc files, not header files, there will be no ODR violation, since the only part whose definition varies is the "using" declaration, which does not have external linkage.

There is still some possibility of clients creating ODR violations if the client header files (rather than .cc files) reference flatbuffers::Verifier. To avoid that, this change also deprecates FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE, and instead introduces flatbuffers::SizeVerifier as a public name for the template instance with the boolean parameter set to true, so that clients don't need to define the macro at all.