开发基于glib的程序时,经常会出现类似如下的log:
** (process:6437): CRITICAL **: xxxxxxxxx: assertion '( func != NULL ) && ( xxx != NULL ) && ( count > 0 )' failed
这时因为某些非致命性的assert失败,从而输出的log,但程序往往仍在运行,该log提供的信息有时又非常有限,无法定位出问题位置。
glib中提供了G_DEBUG这个环境变量,可以通过设置这个环境变量使得该类warning会导致程序trap,使得如gdb一类的调试器能够捕获到程序中断的位置,来加速问题解决。
G_DEBUG的使用如下:
This environment variable can be set to a list of debug options, which cause GLib to print out different types of debugging information.
fatal-warnings Causes GLib to abort the program at the first call to g_warning() or g_critical().
fatal-criticals Causes GLib to abort the program at the first call to g_critical().
gc-friendly Newly allocated memory that isn't directly initialized, as well as memory being freed will be reset to 0. The point here is to allow memory checkers and similar programs that use Boehm GC alike algorithms to produce more accurate results.
resident-modules All modules loaded by GModule will be made resident. This can be useful for tracking memory leaks in modules which are later unloaded; but it can also hide bugs where code is accessed after the module would have normally been unloaded.
bind-now-modules All modules loaded by GModule will bind their symbols at load time, even when the code uses %G_MODULE_BIND_LAZY.
例如,以如下方式运行程序:
G_DEBUG=fatal-warnings gdb ./a.out