Variadic macros with 0 arguments in C99

前端 未结 1 1316

I have some debugging code that looks like the following:

#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ \":\" TOSTRING(__LINE__)
v         


        
相关标签:
1条回答
  • 2021-02-14 05:45

    I see two solutions to this problem. (Three if you count 'stick with gcc').

    Extra special case macro

    Add a new macro for when you want to print a fixed string.

    #define my_errorf(str) my_error(str, NULL)
    

    Pro: Minimum amount of extra code.
    Con: It's easy to use the wrong macro (but at least you notice this at compile time).

    Put fmt inside the '...'

    Vararg macro's can have only __VA_ARGS__ as parameter (unlike vararg functions). So you can put the fmt argument inside the __VA_ARGS__ and change your function.

    void __my_error(const char *loc, ...);
    #define my_error(...) __my_error(AT, __VA_ARGS__)
    

    Pro: One syntax/macro for all error messages.
    Con: Requires rewriting of your __my_error function, which might not be possible.

    0 讨论(0)
提交回复
热议问题