Disable functions using MACROS

前端 未结 2 566
别跟我提以往
别跟我提以往 2021-02-10 05:09

After searching quite a bit in the Internet for a solution I decided to ask here if my solution is fine.

I\'m trying to write a simple and modular C logging library inte

2条回答
  •  生来不讨喜
    2021-02-10 05:41

    The standard idiom for that, at least in the 90s, was:

    #ifndef NLOG
    void logger_init(logger_t *logger);
    void logger_log(logger_t *logger, ...);
    #else
    #define logger_init (void)sizeof
    #define logger_log  (void)sizeof
    #endif
    

    Remember that sizeof operands are not evaluated, although they are syntax checked. This trick works also with variadic functions, because the sizeof operator will see an expresion with several comma operators:

    logger_log(log, 1, 2, 3);
    

    Converts to:

    (void)sizeof(log, 1, 2, 3);
    

    Those commas are not separating parameters (sizeof is not a function but an operator), but they are comma operators.

    Note that I changed the return value from int to void. No real need for that, but the sizeof return would be mostly meaningless.

提交回复
热议问题