Design printf debugging macros according to debug needs

Reprinted from: https://segmentfault.com/a/1190000000456199

v1--Single parameter macro

#define DRV_DEBUG 1
#if DRV_DEBUG
    #define DRV_PRINT(x) printf(x)
#else
    #define DRV_PRINT(x) 
#endif

v2--specify parameter macro

#define DRV_DEBUG 1
#if DRV_DEBUG
    #define DRV_PRINT(fmt, val1, val2) printf(fmt, val1, val2)
#else
    #define DRV_PRINT(fmt, val1, val2) 
#endif

 

v3-Variable number of parameters macro

C90 and C ++, the macro can be declared to accept a variable number of arguments, such as ARM编译器this is :

#define DRV_DEBUG 1
#if DRV_DEBUG
    #define DRV_PRINT(fmt, ...) printf(fmt, __VA_ARGS__)
#else
    #define DRV_PRINT(fmt, ...) 
#endif

Now the DRV_PRINTusage is printfexactly the same, such a cool function, C2000编译器but it does not support it!

A digression, note that this feature is supported by C90, and C90 is a subset of C++, but C99 and C++ are not compatible anymore

 

Hierarchical LOG output

Sometimes, a certain module has input tracking information, output information, error information, etc. If I want to open a certain part of the information separately, I can design it like this

#define DRV_DEBUG 1
#define DRV_DEBUG_IN 0x0001
#define DRV_DEBUG_OUT 0x0002
#define DRV_DEBUG_ERR 0x0004
#define DRV_DEBUG_ALL 0xFFFF
#if DRV_DEBUG
        unsigned int drv_flags = DRV_DEBUG_ERR | DRV_DEBUG_OUT;
    #define DRV_PRINT(flag, fmt, ...) \
            do{\
                if(drv_flags & flag){\
                printf(fmt, __VA_ARGS__)}\
            }while(0)
#else
    #define DRV_PRINT(fmt, ...) 
#endif

NOTE: Multi-line macro, pay attention to the plus \sign before the line break

In this way, I only print OUT and ERR:

void drv_write(char* msg_out)
{
    DRV_PRINT(DRV_DEBUG_OUT, "Drivr write %s", msg_out); // 输出
        DRV_PRINT(DRV_DEBUG_ERR, "Drivr write %s", msg_out); // 输出
        DRV_PRINT(DRV_DEBUG_IN, "Drivr write %s", msg_out); // 不输出
}

Furthermore, LOG output control for different modules of the entire system can be designed! This is how the TCP/IP protocol stack is implemented Lwip!

to sum up

In the embedded C language, the use of printf debugging macros is helpful for post-mortem analysis, positioning BUG, ​​the more the better!

Guess you like

Origin blog.csdn.net/qingfengjuechen/article/details/87990642