读书人

C标准库分析之lt;assert.hgt

发布时间: 2012-12-20 09:53:21 作者: rapoo

C标准库分析之<assert.h>

2011年 03月 03日 星期四 15:47:42 CST

/* "__FILE__"是预定义的宏(也叫内置宏),值是所在文件的文件名(字符串字面量) */
/* "__LINE__"是预定义的宏,值是调用的语句所在文件中的行数(是十进制常量) */
/* assert.h standard header */
#undef assert? /* 良性取消assert定义 */

#ifdef NDEBUG
??? #define assert(test) ((void) 0)??? /* 如果已定义了NDEBUG,那么assert函数不执行任何操作 */
#else
??? void _Assert(char *);
???
??? #define _STR(x) _VAL(x)
??? #define _VAL(x) #x??? /* 井号在此是预处理运算符——字符串化运算符 */
??? #define assert(test) ((test) ? (void) 0 \??? /* "(void) 0"表示什么也不做 */
???? : _Assert(__FILE__ ":" _STR(__LINE__) " " #test))??? /* 使用了条件表达式"a ? b : c" */???
???? /* 理解"_STR(__LINE__)":宏定义里有用'#'或'##'的地方宏参数是不会再展开的 */
#endif

???

/* xassert.c */??? /* 库中隐藏的函数和数据对象通常占据以x开头命名的C源文件 */
/* _Assert function */
#include <assert.h>
#include <stdio.h>??? /* fputs函数在stdio.h中声明 */
#include <stdlib.h>??? /* abort函数在stdlib.h中声明 */

void _Assert(char *mesg)
{
??? fputs(mesg, stderr);??? /* 把字符串写到标准输出流stderr里 */
??? fputs(" -- assertion failed\n", stderr);
??? abort();??? /* 调用函数abort异常终止程序的执行 */
}

/* 源码来自 The Standard C Library, by P.J.Plauger */
/* 代码注释为原创 */

?

读书人网 >编程

热点推荐