Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

c++ - GCC 7, -Wimplicit-fallthrough warnings, and portable way to clear them?

We are catching warnings from GCC 7 for implicit fall through in a switch statement. Previously, we cleared them under Clang (that's the reason for the comment seen below):

g++ -DNDEBUG -g2 -O3 -std=c++17 -Wall -Wextra -fPIC -c authenc.cpp
asn.cpp: In member function ‘void EncodedObjectFilter::Put(const byte*, size_t)’:
asn.cpp:359:18: warning: this statement may fall through [-Wimplicit-fallthrough=]
    m_state = BODY;  // fall through
                  ^
asn.cpp:361:3: note: here
   case BODY:
   ^~~~

The GCC manual states to use __attribute__ ((fallthrough)), but its not portable. The manual also states "... it is also possible to add a fallthrough comment to silence the warning", but it only offer FALLTHRU (is this really the only choice?):

switch (cond)
  {
  case 1:
    bar (0);
    /* FALLTHRU */
  default:
    …
  }

Is there a portable way to clear the fall through warning for both Clang and GCC? If so, then what is it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

GCC expects the marker comment on its own line, like this:

  m_state = BODY;
  // fall through
case BODY:

The marker also has to come right before the case label; there cannot be an intervening closing brace }.

fall through is among the markers recognized by GCC. It's not just FALLTHRU. For a full list, see the documentation of the -Wimplicit-fallthrough option. Also see this posting on the Red Hat Developer blog.

C++17 adds a [[fallthrough]] attribute that can be used to suppress such warnings. Note the trailing semicolon:

  m_state = BODY;
  [[fallthrough]];
case BODY:

Clang supports -Wimplicit-fallthrough warnings, but does not enable them as part of -Wall or -Wextra. Clang does not recognize comment markers, so the attribute-based suppression has to be used for it (which currently means the non-standard __attribute__((fallthrough)) construct for the C front end).

Note that suppressing the warning with marker comments only works if the compiler actually sees the comment. If the preprocessor runs separately, it needs to be instructed to preserve comments, as with the -C option of GCC. For example, to avoid spurious warnings with ccache, you need to specify the -C flag when compiling, or, with recent versions of ccache, use the keep_comments_cpp option.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...