我正在以下列方式打印我的断言声明:
assert((i==0) && "i is not zero");
Output: Assertion 'i==0 && i is not zero' failed.
What I want to be printed:
Output: 'i==0, i is not zero failed.
答案 0 :(得分:2)
你必须编写自己的断言宏。类似的东西:
#include <stdio.h>
#include <stdlib.h>
#undef myassert
#ifndef NDEBUG
#define myassert(test, why) ((test) ? (void) 0 \
: (fprintf(stderr, "%s, %s failed.\n", \
#test, why), abort()))
#else
#define myassert(test, why) ((void) 0)
#endif
并像这样使用它:
myassert(i == 0, "i is not zero");
答案 1 :(得分:1)
然后编写自己的断言宏。 (Ninja&#39; by Ross Ridge。)我的例子,根据Jonathan Leffler的评论进行了大量修改:
#undef my_assert
#ifdef NDEBUG
#define my_assert(expression, errormessage) ((void)0)
#else
#include <stdlib.h>
#include <stdio.h>
#if __STDC_VERSION__-199901L >= 0
#define my_assert(expr, msg) \
((void)( (expr) ? 0 : do_assert(__FILE__, __LINE__, __func__, msg) ))
#elif defined(__GNUC__)
#define my_assert(expr, msg) \
((void)( (expr) ? 0 : do_assert(__FILE__, __LINE__, __FUNCTION__, msg) ))
#else
#define my_assert(expr, msg) \
((void)( (expr) ? 0 : do_assert(__FILE__, __LINE__, NULL, msg) ))
#endif
#ifndef HAVE_DO_ASSERT
#define HAVE_DO_ASSERT
static inline int do_assert(const char *const filename,
const unsigned long linenum,
const char *const funcname,
const char *const msg)
{
if (funcname)
fprintf(stderr, "%s: Line %lu, function %s(): %s\n", filename, linenum, funcname, msg);
else
fprintf(stderr, "%s: Line %lu: %s\n", filename, linenum, msg);
abort();
return 0;
}
#endif
#endif
如果您使用
my_assert(i == 0, "nonzero i!");
在main()
第25行的example.c
功能中,i
非零,您将获得
example.c: Line 25, function main(): nonzero i!
标准错误(加上Aborted.
之类的内容,具体取决于操作系统和C库)。