How to deal with clang's (3.9) -Wexpansion-to-defined warning?
Asked Answered
F

2

20

clang 3.9 has added to -Wall a the warning -Wexpansion-to-defined, which produces

macro expansion producing 'defined' has undefined behaviour

in case defined is used outside an #if expression, including the case of a macro that is then used within an #if expression. For example the following code

// in some file:
#define HAS_GNU (defined(__GNUC__) && !defined(__clang__))

// possibly in another file:
#if defined(__clang__) || HAS_GNU
/* ... */
#endif

produces

test.cc:5:27: warning: macro expansion producing 'defined' has undefined behavior [-Wexpansion-to-defined]
#if defined(__clang__) || HAS_GNU
                          ^
test.cc:3:18: note: expanded from macro 'HAS_GNU'
#define HAS_GNU (defined(__GNUC__) && !defined(__clang__))
                 ^
test.cc:5:27: warning: macro expansion producing 'defined' has undefined behavior [-Wexpansion-to-defined]
test.cc:3:40: note: expanded from macro 'HAS_GNU'
#define HAS_GNU (defined(__GNUC__) && !defined(__clang__))

So what's the 'correct' way to do that?

Fir answered 6/2, 2017 at 17:44 Comment(0)
B
37

You can use #if - #else macros:

#if defined(__GNUC__) && !defined(__clang__)
#define HAS_GNU 1
#else
#define HAS_GNU 0
#endif

Or, if you're willing to change the code that uses HAS_GNU, perhaps more conventional way:

#if defined(__GNUC__) && !defined(__clang__)
#define HAS_GNU
#endif

#if defined(__clang__) || defined(HAS_GNU)
Barraza answered 6/2, 2017 at 17:50 Comment(0)
A
5

If you have this kind of problem with a 3d party pod, you may find this useful

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wexpansion-to-defined"
#import <pop/POP.h>
#pragma clang diagnostic pop
Advisedly answered 23/5, 2018 at 11:17 Comment(2)
this doesn't answer the question. Question isn't about disabling the warnings.Foggia
The questions is "How to deal with...". If you have 3-rd library you obviously cannot make changes in source code. And this is how "How to deal with " this warning, especially if the project treats warning as errorsAdvisedly

© 2022 - 2024 — McMap. All rights reserved.