http://
vincent.blog.chinaunix.net想不到今天实现assert函数也搞了我这么久。。。郁闷。。。
file: assertx.h
- /*
-
* author: vincent.cws2008@gmail.com
-
* history:
-
* initial @ 2011-08-23
-
*/
-
-
#ifndef _ASSERTX_H_
-
#define _ASSERTX_H_
-
-
#include <stdio.h>
-
#include <stdarg.h>
-
-
#define OUTPUT_WHERE OUTPUT_SCREEN
-
-
/* where to output */
-
#define OUTPUT_SCREEN 1
-
#define OUTPUT_FILE 2
-
-
/* halt on */
-
#ifndef unreachable
-
#define unreachable() do {} while (1)
-
#endif
-
-
/* Microsoft VC TOOLS VERSION DEFINITION
-
* MS VC++ 10.0 _MSC_VER = 1600
-
* MS VC++ 9.0 _MSC_VER = 1500
-
* MS VC++ 8.0 _MSC_VER = 1400
-
* MS VC++ 7.1 _MSC_VER = 1310
-
* MS VC++ 7.0 _MSC_VER = 1300
-
* MS VC++ 6.0 _MSC_VER = 1200
-
* MS VC++ 5.0 _MSC_VER = 1100
-
*/
-
-
#if defined(WIN32)&&(_MSC_VER < 1300)
-
-
#define __func__ "?"
-
/* you need define outputx itself under VC6 */
-
extern void outputx(const char* fmt,...);
-
#if OUTPUT_WHERE!=OUTPUT_SCREEN && OUTPUT_WHERE!=OUTPUT_FILE
-
/* no output */
-
#define outputx(fmt,...)
-
#endif
-
-
#else
-
-
#define __func__ __FUNCTION__
-
/* output to screen */
-
#if OUTPUT_WHERE==OUTPUT_SCREEN
-
#define outputx(fmt,...) \
-
do { \
-
printf(##fmt, ##__VA_ARGS__); \
-
}while(0)
-
/* output to file */
-
#elif OUTPUT_WHERE==OUTPUT_FILE
-
extern void outputx(const char* fmt,...);
-
#else
-
/* no output */
-
#define outputx(fmt,...)
-
#endif
-
-
#endif
-
-
/* go on the next step after assert(0) */
-
#define assertx_goon(expr) \
-
do { \
-
if (!(expr)) { \
-
outputx("Assertion failed! %s, %s, %s, line %d\n", \
-
#expr, __FILE__, __func__, __LINE__); \
-
} \
-
}while(0)
-
-
/* halt after assert(0) */
-
#define assertx_halt(expr) \
-
do { \
-
if (!(expr)) { \
-
outputx("Assertion failed! %s, %s, %s, line %d\n", \
-
#expr, __FILE__, __func__, __LINE__); \
-
unreachable();\
-
} \
-
}while(0)
-
-
-
#endif
file: main.c
- /*
-
* author: vincent.cws2008@gmail.com
-
* history:
-
* initial @ 2011-08-23
-
*/
-
-
#include "assertx.h"
-
-
#ifdef WIN32
-
#define vsnprintf _vsnprintf
-
#endif
-
-
#define MAX_OUTPUT 100
-
-
void outputx(const char* fmt,...)
-
{
-
int ret;
-
char buf[MAX_OUTPUT];
-
va_list args;
-
va_start(args, fmt);
-
ret = vsnprintf(buf, sizeof(buf), fmt, args);
-
buf[MAX_OUTPUT-1]=0;
-
if(ret<0){
-
printf("warning: output has been truncated!");
-
}
-
printf ("%s", buf);
-
va_end(args);
-
}
-
-
int main(int argc, char* argv[])
-
{
-
assertx_goon(0);
-
assertx_halt(0);
-
return 0;
-
}
附件:
assertx.rar
阅读(1276) | 评论(0) | 转发(0) |