c,assert 宏的实现

预备知识:
#define _VAL(x) #x    //#x的作用就是把x表达式变成一个字符串。(注意 : 不带换行符'\n' , 换行符ascii==10)。
如:_STR(i<100)
printf("%s\n" , _STR(i<100)) ;会在终端打印 i<100。

下面来实现assert宏,和标准库的同样功能,可打印出错的”文件、行、表达式“:
//massert.c
#include "massert.h" #include <stdlib.h> #include <stdio.h> void _mAssert(char * mesg) { fputs(mesg, stderr); fputs("--assertion failed\n", stderr); abort(); }
//massert.h
#ifndef NDEBUG
    extern void _mAssert(char *);
    #define _STR(x)  _VAL(x)
    #define _VAL(x)  #x
    #define massert(test)    \
        ((test)? (void)0 : _mAssert(__FILE__ ":" _STR(__LINE__) " " #test))
#else 
    #define massert(test) 
#endif
//demo1.c
#include "massert.h"

int func1(int i )
{
    massert(i<150);
    return 2*i;    
}
//demo2.c
#define NDEBUG
#include "massert.h"

int func2(int i )
{
    massert(i<150);
    return 2*i;    
}
//demo.c
#include <stdio.h> extern int func2(int i ); extern int func2(int i ); int main() { if(1){ printf("11111\n"); func1(100); printf("22222\n"); func1(200); }else{ printf("33333\n"); func2(100); printf("44444\n"); func2(200); } return 0; }
//终端打印结果:
//if(1)
11111
22222
demo1.c:7 i<150--assertion failed
Aborted

//if(0)
33333
44444
实现了assert宏,和标准库的同样功能。可打印出错的”文件、行、表达式“。

 

没有系统的时候,怎么实现一个assert?

//massert, 当出现test的情况,报错并返回error_code
#define _STR(x)  _VAL(x)
#define _VAL(x)  #x
#define massert(test, error_code)\
    if((test)){\
        printf("In file "__FILE__ ",Line " _STR(__LINE__) "," #test"\n");\
        return error_code;\
    }

int main()
{
    massert(1>0, 0xff);
    massert(-1>0, 0xff);
    return 0;
}
//In file main.c,Line 13,1>0

 

posted @ 2015-01-08 16:50  oucaijun  阅读(1144)  评论(0编辑  收藏  举报
下载TeamViewer完整版 下载TeamViewer