Pietro
Pietro

Reputation: 13222

Define a macro to be run at global scope without warnings

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.

Upvotes: 1

Views: 184

Answers (2)

Pietro
Pietro

Reputation: 13222

This solution seems to be reasonable:

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

INIT;

int main() { ... }

Upvotes: 0

Vittorio Romeo
Vittorio Romeo

Reputation: 93384

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.

Upvotes: 2

Related Questions