1

The following code is OK, but I get a warning due to the extra ';' after INIT.

#define INIT \
    namespace Vars { \
      int a = 0; \
    }

INIT;

int main() { ... }

How can I fix this code, allowing the notation with the extra ';'?

Consider that INIT must be callable at global scope.

Pietro
  • 12,086
  • 26
  • 100
  • 193

2 Answers2

2

If you really want to force the semicolon, one possible workaround is defining an unused struct with a "unique" name, like this:

#define CAT_IMPL(m0, m1) m0##m1
#define CAT(m0, m1) CAT_IMPL(m0, m1)

#define INIT \
    namespace Vars { \
      \
    } \
    struct CAT(some_unique_name, __LINE__) \
    { } __attribute__((unused))

INIT;
INIT;

int main() { }

Coliru example here.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416
  • That's neat, but notice that it breaks compatibility with MSVC. – Christian Hackl Nov 01 '15 at 10:53
  • Thank you Vittorio, but I would say that instead of using that slightly cryptic code I prefer to get the warning. – Pietro Nov 02 '15 at 10:35
  • @Pietro: if you are satisfied, do you mind accepting this answer so that the question can be marked as "solved"? Thanks. Alternatively, you can post your own answer and accept it. – Vittorio Romeo Jan 07 '16 at 17:23
0

This solution seems to be reasonable:

#define INIT \
    namespace Vars { \
      int a = 0; \
    } int INIT_ = 0

INIT;

int main() { ... }
Pietro
  • 12,086
  • 26
  • 100
  • 193