断言带有时间戳的失败时是否有可能记录信息
前任。
int a = 10
assert( a > 100 );
那么它将失败并输出与时间戳相同的结果
2013-12-02 , 17:00:05 assert failed !! (a > 100) line : 22
谢谢
assert
是一个宏(它必须是一个,以得到__LINE__
和__FILE__
信息)。
您可以定义自己的。tassert
由于可读性原因,我可能会用其他名称来命名,例如(未经测试的代码)
#ifdef NDEBUG
#define tassert(Cond) do {if (0 && (Cond)) {}; } while(0)
#else
#define tassert_at(Cond,Fil,Lin) do { if ((Cond)) { \
time_t now##Lin = time(NULL); \
char tbuf##Lin [64]; struct tm tm##Lin; \
localtime_r(&now##Lin, &tm##Lin); \
strftime (tbuf##Lin, sizeof(tbuf##Lin), \
"%Y-%m-%d,%T", &tm##Lin); \
fprintf(stderr, "tassert %s failure: %s %s:%d\n", \
#Cond, tbuf##Lin, Fil, Lin); \
abort(); }} while(0)
#define tassert(Cond) tassert_at(Cond,__FILE__,__LINE__)
#endif /*NDEBUG*/
我使用的CPP串联 ##
与Lin
降低名称冲突的概率,而我使用的CPP字串 #
做出串出的Cond
宏观形式。将Cond
始终扩大,一定要确保编译器捕获的语法错误禁用,即使tassert
与NDEBUG
作为断言(3)一样。
可以通过某种功能将大部分代码放在上述宏中,例如
void tassert_at_failure (const char* cond, const char* fil, int lin) {
timer_t now = time(NULL);
char tbuf[64]; struct tm tm;
localtime_r (&now, &tm);
strftime (tbuf, sizeof(tbuf), "%Y-%m-%d,%T", &tm);
fprintf (stderr, "tassert %s failure: %s %s:%d\n",
cond, tbuf, fil, lin);
abort();
}
然后定义(有点像<assert.h>
...)
#define tassert_at(Cond,Fil,Lin) do { if ((Cond)) { \
tassert_at_failure(#Cond, Fil, Lin); }} while(0)
但我不喜欢多,做法,因为与调试gdb
已经 abort()
被称为在宏的代码调试可执行文件更容易(恕我直言大小并不在所有问题;呼吁abort
在宏是方便多内gdb
-使短回溯并避免使用一条down
命令...)。如果您不想要libc
可移植性,而只是使用最新的GNU libc
,则可以简单地重新定义Glibc特定的__assert_fail
功能(请参阅<assert.h>
头文件中的内容)。YMMV。
顺便说一句,在实际的C ++代码中,我更喜欢将其<<
用于类似断言的调试输出。这样可以使用我自己的operator <<
输出例程(如果您将其作为附加的宏参数提供),因此我正在考虑(未经测试的代码!)
#define tassert_message_at(Cond,Out,Fil,Lin) \
do { if ((Cond)) { \
time_t now##Lin = time(NULL); \
char tbuf##Lin [64]; struct tm tm##Lin; \
localtime_r(&now##Lin, &tm##Lin); \
strftime (tbuf##Lin, sizeof(tbuf##Lin), \
"%Y-%m-%d,%T", &tm##Lin); \
std::clog << "assert " << #Cond << " failed " \
tbuf##Lin << " " << Fil << ":" << Lin \
<< Out << std::endl; \
abort (); } } while(0)
#define tassert_message(Cond,Out) \
tassert_message_at(Cond,Out,__FILE__,__LINE__)
然后我会用 tassert_message(i>5,"i=" << i);
顺便说一句,您可能要使用syslog(3)而不是fprintf
在tassert_at
宏中使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句