我想创建我自己的 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/