c - 如何覆盖C中的断言宏?

标签 c assert ld-preload ndebug

我想创建我自己的 assert 版本,其中它会打印一些日志,以防在 NDEBUG 模式下调用断言。

我尝试使用 LD_PRELOAD 技巧并重新定义 assert 宏,但它似乎完全忽略了宏定义并且覆盖 __assert_fail 无关紧要,因为在 NDEBUG 的情况下不会调用它。

如何覆盖 libc assert 宏?

我不想创建不同的函数,因为 assert 已经在项目中大量使用。

最佳答案

在 Cygwin/Windows 和 Linux 上使用 gcc 时遇到了同样的问题。

我的解决方案是覆盖实际断言失败处理函数的(弱)定义。这是代码:

/*!
 * Overwrite the standard (weak) definition of the assert failed handling function.
 *
 * These functions are called by the assert() macro and are named differently and
 * have different signatures on different systems.
 * - On Cygwin/Windows its   __assert_func()
 * - On Linux its            __assert_fail()
 *
 * - Output format is changed to reflect the gcc error message style
 *
 * @param filename    - the filename where the error happened
 * @param line        - the line number where the error happened
 * @param assert_func - the function name where the error happened
 * @param expr        - the expression that triggered the failed assert
 */
#if defined( __CYGWIN__ )

void __assert_func( const char *filename, int line, const char *assert_func, const char *expr )

#elif defined( __linux__ )

void __assert_fail ( const char* expr, const char *filename, unsigned int line, const char *assert_func )

#else
# error "Unknown OS! Don't know how to overwrite the assert failed handling function. Follow assert() and adjust!"
#endif
{
    // gcc error message style output format:
    fprintf( stdout, "%s:%d:4: error: assertion \"%s\" failed in function %s\n",
             filename, line, expr, assert_func );

    abort();
}

关于c - 如何覆盖C中的断言宏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35578614/

相关文章:

c - YACC 文件是否有文件包含机制?

d - 停止代码编译

java - 如果日期相同,为什么 assertEquals 为假? hibernate

linux - 拦截所有二进制文件的打开系统调用

c - LD_PRELOAD 是否可能只影响主可执行文件?

c++ - 某些可执行文件的 LD_PRELOAD 和 calloc() 插入问题

c - 如何模拟 os x 上的低级按键?

c - 为什么这个程序在用户信号处理程序之后没有终止

C编译错误,调用的对象不是函数

xml - XML Schema 1.0 中是否有 <assert> 的替代方案