Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C Programming (http://www.velocityreviews.com/forums/f42-c-programming.html)
-   -   Re: Expanding macros within #error (http://www.velocityreviews.com/forums/t807276-re-expanding-macros-within-error.html)

Kaz Kylheku 12-22-2011 11:40 PM

Re: Expanding macros within #error
 
On 2011-12-22, Kenneth Brody <kenbrody@spamcop.net> wrote:
> Is there any "trick", or is this just one of those "sorry, you can't do
> that" things?


I just thought of an ugly one:

#define str(x) #x
#define bad_symbol_value_error(x) str(macro_ ## x has bad value x)
#define foo 42
#include bad_symbol_value_error(foo)

$ gcc test.c
test.c:4: fatal error: macro_foo has bad value 42: No such file or directory
compilation terminated.

:)

Kaz Kylheku 12-22-2011 11:49 PM

Re: Expanding macros within #error
 
On 2011-12-22, Kaz Kylheku <kaz@kylheku.com> wrote:
> On 2011-12-22, Kenneth Brody <kenbrody@spamcop.net> wrote:
>> Is there any "trick", or is this just one of those "sorry, you can't do
>> that" things?

>
> I just thought of an ugly one:
>
> #define str(x) #x
> #define bad_symbol_value_error(x) str(macro_ ## x has bad value x)
> #define foo 42
> #include bad_symbol_value_error(foo)
>
> $ gcc test.c
> test.c:4: fatal error: macro_foo has bad value 42: No such file or directory
> compilation terminated.


Here is a variation on a theme: another way of forcing the preprocessor into
generating an error message which includes both "foo" and its expansion, if it
has one:

#define bad_value_ex(x, y) x ## y
#define bad_value(x) bad_value_ex(#x, x)
#define foo 42
bad_value(foo)

$ gcc test.c
test.c:4: error: pasting ""foo"" and "42" does not give a valid preprocessing token
test.c:4: error: expected identifier or ‘(’ before string constant

I think this is relying on undefined behavior. If I recall, bad token pastes do
not require a diagnostic, but I don't care enough to look it up.


All times are GMT. The time now is 02:35 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.