Re: Expanding macros within #error

Discussion in 'C Programming' started by Kaz Kylheku, Dec 22, 2011.

  1. Kaz Kylheku

    Kaz Kylheku Guest

    On 2011-12-22, Kenneth Brody <> 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, Dec 22, 2011
    #1
    1. Advertising

  2. Kaz Kylheku

    Kaz Kylheku Guest

    On 2011-12-22, Kaz Kylheku <> wrote:
    > On 2011-12-22, Kenneth Brody <> 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.
     
    Kaz Kylheku, Dec 22, 2011
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Replies:
    80
    Views:
    2,536
    Stephen J. Bevan
    Nov 7, 2003
  2. Replies:
    1
    Views:
    497
    Marco Antoniotti
    Oct 7, 2003
  3. Replies:
    5
    Views:
    516
  4. Michael T. Babcock

    Re: Explanation of macros; Haskell macros

    Michael T. Babcock, Nov 3, 2003, in forum: Python
    Replies:
    0
    Views:
    543
    Michael T. Babcock
    Nov 3, 2003
  5. Anthony de Almeida Lopes

    Macros within function-like macros?

    Anthony de Almeida Lopes, Dec 26, 2005, in forum: C Programming
    Replies:
    13
    Views:
    791
Loading...

Share This Page