Multiple errors from C assert macro

Viewed 438

I have a assert macro that's defined as:

#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__ ))

Which works fine, except when you make a simple error inside an assert condition, eg a wrong variable name:

assert(size > 0);

It prints a perfectly sensible error, then 5 notes (including repeats) which makes it much harder to read. Is there any sane way to address this that would make it easier to read? The core issue seems to be the use of macros, but I can't see how to avoid that here, given the use of __FILE__, __LINE__, etc.

Disabling the "note: each undeclared identifier is reported only once for each function" would cut it in half if that was possible (though I cannot find any way to do that)

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);
     ^
2 Answers
Related