一个简单的GNU assert用法测试程序

来源:互联网 发布:淘宝代购基本都是假货 编辑:程序博客网 时间:2024/06/05 05:20
/*********************************************************************
 * Function: Test assert
 * Author  : Samson
 * Date    : 12/12/2011
 * Test platform:
 *               GNU Linux version 2.6.29.4
 *               gcc version 4.4.0 20090506 (Red Hat 4.4.0-4) (GCC)
 * *******************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>


int
main(int argc, char *argv[])
{

  assert(argc != 2);
  printf("argc is %d\n", argc);
  exit(0);  

}

assert当在条件为false的时候程序会被中断,它的用处在开发人员进行调试时非常有用,能够准确的定位到出错的文件:函数:行号。当不加NDEBUG宏时,此测试程序的输出为:
a.out: testassert.c:9: main: Assertion `argc != 2' failed.
已放弃

但在进行程序发行版本的时候,用户不希望这样突然直接的给中断了,对用户要"
柔和",柔和的话就使用有提示的if语句或打印等。

柔和版本的编译方式为:gcc testassert.c -DNDEBUG
run result:
[root@UFO testc]# ./a.out 2
argc is 2

直言直去版本编译方式为:gcc testassert.c
run result:
[root@UFO testc]# ./a.out 2
a.out: testassert.c:9: main: Assertion `argc != 2' failed.
已放弃