多用assert,能很好找到程序出错位置。
/* 断言。当f为假时,输出当前断言的表达式,及代码所在位置的信息(函数名、源文件名、行号),并退出程序,返回-1。 */
#define ASSERT()/
printf("__funtion__:%s(), __file__:%s, __line__:%d/n",__func__,__FILE__,__LINE__)
#define ASSERT_MSG(f,msg) /
if (!(f)){ /
printf("***ERROR***(%s): /"%s/" must be true, __funtion__:%s(), __file__:%s, "/
"__line__:%d/n",msg,#f,__func__,__FILE__,__LINE__); /
exit(-1); /
}
#define ASSERT_MSG_FMT(f,fmt,args...) /
if (!(f)){ /
printf("***ERROR***: /"%s/" must be true, __funtion__:%s(), __file__:%s, "/
"__line__:%d/n",#f,__func__,__FILE__,__LINE__); /
printf(fmt,##args); /
printf("/n"); /
exit(-1); /
}
/** 注意,如果上面换行时,不多加两个引号,则输出时,下一行前面的空格也行被输出。 */
void fun(char* str1,char* str2)
{
// ASSERT();
ASSERT_MSG(!strcmp(str1,str2),"the two string isn't equal");
}
/**
* 判断输入两个参数是否相等
*/
int main(int argc,char *argv[])
{
printf("this is a test for assert,by yuanzhenhai/n");
// ASSERT();
ASSERT_MSG(argc == 3,"argc != 3");
fun(argv[1],argv[2]);
printf("the two strings that you input is equal,successful!/n");
return 0;
}
测试
1、输入参数个数不等于2时
yuan@yuan:~/work/test> ./assert test
this is a test for assert,by yuanzhenhai
***ERROR***(argc != 3): "argc == 3" must be true, __funtion__:main(), __file__:assert.c, __line__:42
2、输入参数个数等于2,但两个参数字符串不相等时
yuan@yuan:~/work/test> ./assert test testtt
this is a test for assert,by yuanzhenhai
***ERROR***(the two string isn't equal): "!strcmp(str1,str2)" must be true, __funtion__:fun(), __file__:assert.c, __line__:32
3、输入参数个数等于2,两个参数字符串也相等时
yuan@yuan:~/work/test> ./assert test test
this is a test for assert,by yuanzhenhai
the two strings that you input is equal,successful!