c->log技巧

介绍:

  在C代码里,有时会加入一些打印信息方便分析问题,可用如下代码替代打印函数,更加方便。

//
// Created by lady on 18-12-10.
//


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define DEBUG

#ifdef DEBUG
#include <stdarg.h>
#define LOG(args...) _log_(__FILE__, __FUNCTION__, __LINE__, ##args);
static void _log_(const char *file, const char *function, int line, const char * format, ...)
{
    char buf[1024] = {0};
    va_list list;
    va_start(list, format);
    sprintf(buf, "[%s,%s,%d]", file, function, line);
    vsprintf(buf+strlen(buf), format, list);
    sprintf(buf+strlen(buf), "
");
    va_end(list);
    printf(buf);
}
#else
#define LOG
#endif // DEBUG

int main(int argc, char *argv[])
{
    LOG("test1");
    return 0;
}
/home/lady/CLionProjects/untitled/cmake-build-debug/untitled
[/home/lady/CLionProjects/untitled/main.c,main,48]test
[/home/lady/CLionProjects/untitled/main.c,main,49]test1

Process finished with exit code 0
原文地址:https://www.cnblogs.com/aimmiao/p/10368329.html