参考链接:1 ((sizeof(n)+sizeof(int)-1)&~(sizeof(int)-1))

                    2 对C语言中va_list,va_start,va_arg和va_end的一点理解 

                    3 C 库宏 - va_start()

                    4  vsnprintf函数用法

                    5 C,C++宏中#、##和__VA_ARGS__的理解

                    6 C语言中函数参数的省略号

                    7 函数参数带省略号的用法

                   8 调试技巧——宏定义开关和printf

                   9 怎样写参数个数可变的宏

                  10 __VA_ARGS__用法

main.c

#include <stdio.h>
#include "Debug.h"

int main(int argc, char *argv[])
{
	int data = 999;
    printDebugMsg("TestProgram", "data= %d", data);
	printf("Hello C-Free!\n");
	return 0;
}

Debug.h

#ifndef __DEBUG_H__
#define __DEBUG_H__

#ifdef __cplusplus
	extern "C" {
#endif

#include <stdio.h>
#include <stdarg.h>

#define _DEBUG
#ifdef  _DEBUG
	//#define DEBUG_TO_FILE
	#ifdef  DEBUG_TO_FILE
	//调试信息输出到以下文件
	#define DEBUG_FILE "..//tmp//debugmsg.txt" 
	//调试信息的缓冲长度 
	#define DEBUG_BUFFER_MAX    4096
    //将调试信息输出到文件中
	#define printDebugMsg(moduleName, format, ...) {\
	char buffer[DEBUG_BUFFER_MAX+1] = {0};\
	snprintf(buffer, DEBUG_BUFFER_MAX,\
			"[%s] "format" File:%s, Line:%d\n", moduleName, ##__VA_ARGS__, __FILE__, __LINE__);\
	FILE* fd = fopen(DEBUG_FILE, "a");\
	if(fd != NULL){\
		fwrite(buffer, strlen(buffer), 1, fd);\
		fflush(fd);\
		fclose(fd);\
		}\
	}
	#else //#ifndef  DEBUG_TO_FILE
	//将调试信息输出到终端 
	#define printDebugMsg(moduleName, format, ...)\
	                printf("[%s] "format" File:%s, Line:%d\n", moduleName, ##__VA_ARGS__, __FILE__, __LINE__);
 
	#endif //end for #ifdef DEBUG_TO_FILE
#else
	//发行版本,什么也不做 
    #define printDebugMsg(moduleName, format, ...)
#endif //end for #ifdef _DEBUG 



/*--------------------Private Function------------------------*/
extern void printfDebugMsg(const char* format, ...);

#ifdef __cplusplus
	}
#endif


#endif /*__DEBUG_H__*/

/******************* (C) COPYRIGHT 2018  *****END OF FILE****/

Debug.c

#include "Debug.h"

#define DEBUG_BUFFER_MAX    4096

/*
只有支持C99规范的gcc编译器才有__VA_ARGS__这个宏,
如果不是gcc编译器,或者所用的gcc编译器版本不支持__VA_ARGS__宏怎么办
*/

void printfDebugMsg( const char* format, ...)
{
	 char buffer[DEBUG_BUFFER_MAX + 1]={0};
	 va_list arg;
	 va_start (arg, format);
	 vsnprintf(buffer, DEBUG_BUFFER_MAX, format, arg);
	 va_end (arg);
	 printf( "%s", buffer );
}

测试结果:

建立Debug调试日志

相关文章: