How do you create a debug only function that takes a variable argument list? Like printf()

后端 未结 14 2163
心在旅途
心在旅途 2020-12-23 09:44

I\'d like to make a debug logging function with the same parameters as printf. But one that can be removed by the pre-processor during optimized builds.

<
14条回答
  •  梦毁少年i
    2020-12-23 10:11

    Part of the problem with this kind of functionality is that often it requires variadic macros. These were standardized fairly recently(C99), and lots of old C compilers do not support the standard, or have their own special work around.

    Below is a debug header I wrote that has several cool features:

    • Supports C99 and C89 syntax for debug macros
    • Enable/Disable output based on function argument
    • Output to file descriptor(file io)

    Note: For some reason I had some slight code formatting problems.

    #ifndef _DEBUG_H_
    #define _DEBUG_H_
    #if HAVE_CONFIG_H
    #include "config.h"
    #endif
    
    #include "stdarg.h"
    #include "stdio.h"
    
    #define ENABLE 1
    #define DISABLE 0
    
    extern FILE* debug_fd;
    
    int debug_file_init(char *file);
    int debug_file_close(void);
    
    #if HAVE_C99
    #define PRINT(x, format, ...) \
    if ( x ) { \
    if ( debug_fd != NULL ) { \
    fprintf(debug_fd, format, ##__VA_ARGS__); \
    } \
    else { \
    fprintf(stdout, format, ##__VA_ARGS__); \
    } \
    }
    #else
    void PRINT(int enable, char *fmt, ...);
    #endif
    
    #if _DEBUG
    #if HAVE_C99
    #define DEBUG(x, format, ...) \
    if ( x ) { \
    if ( debug_fd != NULL ) { \
    fprintf(debug_fd, "%s : %d " format, __FILE__, __LINE__, ##__VA_ARGS__); \
    } \
    else { \
    fprintf(stderr, "%s : %d " format, __FILE__, __LINE__, ##__VA_ARGS__); \
    } \
    }
    
    #define DEBUGPRINT(x, format, ...) \
    if ( x ) { \
    if ( debug_fd != NULL ) { \
    fprintf(debug_fd, format, ##__VA_ARGS__); \
    } \
    else { \
    fprintf(stderr, format, ##__VA_ARGS__); \
    } \
    }
    #else /* HAVE_C99 */
    
    void DEBUG(int enable, char *fmt, ...);
    void DEBUGPRINT(int enable, char *fmt, ...);
    
    #endif /* HAVE_C99 */
    #else /* _DEBUG */
    #define DEBUG(x, format, ...)
    #define DEBUGPRINT(x, format, ...)
    #endif /* _DEBUG */
    
    #endif /* _DEBUG_H_ */
    

提交回复
热议问题