Matt Clarkson
Matt Clarkson

Reputation: 14426

Macro that swallows semicolon outside of function

Is there any idiom that forces a semicolon after a cpp macro outside of a function?

The known solution for macros used inside functions is:

#define MACRO(x) \
  do {
    x * 2;
  } while(0)

However, say I have a macro that looks like the following:

#define DETAIL(warning) _Pragma(#warning)
#define WARNING_DISABLE(warning) DETAIL(GCC diagnostic ignore warning)

What can I put in the macro that would force a semi-colon after that statement. The statement could be used in or outside of a function:

WARNING_DISABLE("-Wunused-local-typedefs")
#include "boost/filesystem.hpp"
void foo(const int x) {
    WARNING_DISABLE("-Wsome-warning")
    ...
}

Is there any C/C++ syntax that will force a semi-colon in the parser at any point in a file that doesn't have side effects?

Edit: A possible use case:

#define MY_CPPUNIT_TEST_SUITE(test_suite_class) \
  WARNING_PUSH \
  /* the declaration of the copy assignment operator has been suppressed */ \
  INTEL_WARNING_DISABLE(2268) \
  /* the declaration of the copy assignment operator has been suppressed */ \
  INTEL_WARNING_DISABLE(2270) \
  /* the declaration of the copy constructor operator has been suppressed */ \
  INTEL_WARNING_DISABLE(2273) \
  CPPUNIT_TEST_SUITE(test_suite_class); \
  WARNING_POP \
  /* force a semi-colon */ \
  UDP_KEYSTONE_DLL_LOCAL struct __udp_keystone_cppunit_test_suite ## __LINE__ {}

Upvotes: 12

Views: 3426

Answers (3)

user2224044
user2224044

Reputation: 111

You don't need LINE trick - it is enough to forward-declare some structure, which is allowed multiple times and there is no need for actual definition. Also collision with actual struct should not be a problem.

#define DETAIL(warning) _Pragma(#warning) struct dummy

Upvotes: 10

Jens Gustedt
Jens Gustedt

Reputation: 78923

The easiest is an extern function declaration

#define MACRO_END_(LINE) extern void some_inprobable_long_function_name ## LINE(void)
#define MACRO_END MACRO_END_(__LINE__)

the line trick is only there because some compilers with excessive warnings give you warnings on duplicate declarations.

This macro works in any context where a declaration is allowed, so with C99 almost everywhere:

#define DETAIL(warning) _Pragma(#warning) MACRO_END

Upvotes: 3

#define DETAIL(warning) _Pragma(#warning) struct X ## __LINE__ {}

Upvotes: 6

Related Questions