Disable functions using MACROS

前端 未结 2 547
别跟我提以往
别跟我提以往 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:18

    Can't your disabled version simply be a constant:

    #ifndef NLOG /* NLOG not defined -> enable logging */
    int logger_init(logger_t *logger) {
    ...
    }
    #else  /* NLOG defined --> the logging system must be disabled */
    #define logger_init(logger)     0
    #endif /* NLOG */
    

    This way, you just have (after pre-compilation): result = 0; which shouldn't produce any warnings.

    0 讨论(0)
  • 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.

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