在Mingw中打印堆栈跟踪

4

我需要修改现有的C应用程序,并在特定位置打印堆栈跟踪信息。我该如何做?

我无法编译此源代码:

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#ifndef __USE_GNU
#define __USE_GNU
#endif

#include <execinfo.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ucontext.h>
#include <unistd.h>


int main(int argc, char ** argv)
{
 void *             array[50];
 void *             caller_address;
 char **            messages;

 int size = backtrace(array, 50);

 /* overwrite sigaction with caller's address */
 array[1] = caller_address;

 messages = backtrace_symbols(array, size);

 /* skip first stack frame (points here) */
 for (int i = 1; i < size && messages != NULL; ++i)
 {
  fprintf(stderr, "[bt]: (%d) %s\n", i, messages[i]);
 }

 free(messages);


}

因为它缺少一些符号:

$ i586-mingw32msvc-gcc -rdynamic ./trace.cpp -I/usr/include/
i586-mingw32msvc-gcc: unrecognized option '-rdynamic'
./trace.cpp:39:2: warning: no newline at end of file
/tmp/cc6hCJtU.o:trace.cpp:(.text+0x26): undefined reference to `_backtrace'
/tmp/cc6hCJtU.o:trace.cpp:(.text+0x47): undefined reference to `_backtrace_symbols'
/tmp/cc6hCJtU.o:trace.cpp:(.text+0x67): undefined reference to `_stderr'

我没有成功生成正确的 .a 文件。

以下是在stackoverflow上找到的答案,但实际上都无法使用:

是否有可行的解决方案?非常感谢。


我需要一个调试器实现,你能否指导一下你在项目中是如何做的?另外,你能否给我提供你所做的示例实现?这将非常有帮助。 - Ragav
1个回答

0

你的MinGW工具链不支持-rdynamic标志,无法使用backtrace()backtrace_symbols()编译应用程序。

不确定你使用的是哪个MinGW版本,但我建议从这里获取最新版本:http://mingw-w64.sourceforge.net/


4
你是在暗示最新的MinGW修复了这个问题吗?如果不是,请澄清一下。 - Aleksandr Dubinsky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接