【发布时间】:2017-08-14 15:43:34
【问题描述】:
我有一个断言宏定义为:
#define likely(cond) (__builtin_expect((cond), 1))
#define unlikely(cond) (__builtin_expect(!!(cond), 0))
static void assert_fail(const char *__assertion, const char *__file,
unsigned int __line, const char *__function) {
fprintf(stderr, "\nASSERT failed %s:%d %s()\n%s\n", __file, __line, __function, __assertion);
void *array[50];
size_t size = backtrace(array, 50); // Fill out array of pointers to stack entries
backtrace_symbols_fd(&array[1], size, STDERR_FILENO);
exit(1);
}
#define assert(expr) ( likely(expr) ? (void) (0) : \
assert_fail(#expr, __FILE__, __LINE__, __func__ ))
这很好用,除非你在断言条件中犯了一个简单的错误,例如错误的变量名:
assert(size > 0);
它会打印一个完全合理的错误,然后是 5 个注释(包括重复),这使得它更难阅读。有没有什么理智的方法可以解决这个问题,使它更容易阅读?核心问题似乎是宏的使用,但鉴于__FILE__、__LINE__等的使用,我看不出如何避免这种情况。
如果可能的话,禁用“注意:每个未声明的标识符只为每个函数报告一次”会减少一半(尽管我找不到任何方法)
abc.c: In function 'init':
abc.c:53:12: error: 'size' undeclared (first use in this function)
assert(size > 0);
^
include/assert.h:21:41: note: in definition of macro 'likely'
#define likely(cond) (__builtin_expect((cond), 1))
^
abc.c:53:5: note: in expansion of macro 'assert'
assert(size > 0);
^
abc.c:53:12: note: each undeclared identifier is reported only once for each function it appears in
assert(size > 0);
^
include/assert.h:21:41: note: in definition of macro 'likely'
#define likely(cond) (__builtin_expect((cond), 1))
^
abc.c:53:5: note: in expansion of macro 'assert'
assert(size > 0);
^
【问题讨论】:
-
第一条错误消息足以诊断此问题。像往常一样修复它
-
我从 gcc 切换到 clang 并且大部分都修复了它。在这种情况下,错误消息似乎得到了更好的考虑,据称还有许多其他错误消息。
标签: c error-handling assert