Are there some better ways to address warnings when compiling protocol buffer generated source file?

后端 未结 3 995
长发绾君心
长发绾君心 2021-01-11 09:52

For a simple proto file:

message Person {
  required int32 id = 1;
  required string name = 2;
  optional string email = 3;
}

It\'s been compiled by pr

相关标签:
3条回答
  • 2021-01-11 09:59

    The compiler is right to give you those warnings, as there is a risk of truncation.

    If the conversions are safe, use explicit casts. This is cleaner than blindly disabling the warnings.

    0 讨论(0)
  • 2021-01-11 10:07

    A simple approach is to use a wrapper header for including the generated protobuf headers:

    #ifndef MESSAGES_WRAPPER_H
    #define MESSAGES_WRAPPER_H
    
    #ifdef _MSC_VER
      #pragma warning(push)
      #pragma warning(disable: 4018 4100 4267)
    #endif
    
    #include "messages.pb.h"
    
    #ifdef _MSC_VER
      #pragma warning(pop)
    #endif
    
    #endif // MESSAGES_WRAPPER_H
    
    0 讨论(0)
  • 2021-01-11 10:18

    You can hack the source of the protoc compiler to have it inject the pragmas into the generated files automatically.

    In src/google/protobuf/compiler/cpp/cpp_file.cc in GenerateHeader(io::Printer* printer) around line 94, change the first printer->Print call to:

      // Generate top of header.
      printer->Print(
        "// Generated by the protocol buffer compiler.  DO NOT EDIT!\n"
        "// source: $filename$\n"
        "\n"
        "#ifndef PROTOBUF_$filename_identifier$__INCLUDED\n"
        "#define PROTOBUF_$filename_identifier$__INCLUDED\n"
        "\n"
        "#ifdef _MSC_VER\n"
        "#  pragma warning(push)\n"
        "#  pragma warning(disable: 4127 4244 4267)\n"
        "#endif\n"
        "\n"
        "#include <string>\n"
        "\n",
        "filename", file_->name(),
        "filename_identifier", filename_identifier);
    

    Then at the end of the same function at around line 294, change the last printer->Print call to:

      printer->Print(
        "#ifdef _MSC_VER\n"
        "#  pragma warning(pop)\n"
        "#endif\n"
        "\n"
        "#endif  // PROTOBUF_$filename_identifier$__INCLUDED\n",
        "filename_identifier", filename_identifier);
    

    Now you just need to compile the protoc target and run the new protoc.exe to have the pragmas in the generated headers.

    0 讨论(0)
提交回复
热议问题