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

家住魔仙堡 提交于 2019-12-01 02:36:40

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.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!