在C或C打印调用栈++ [英] print call stack in C or C++
问题描述
有什么办法倾倒在C或C ++每次运行过程中调用堆栈一定的函数被调用?我心目中是这样的:
Is there any way to dump the call stack in a running process in C or C++ every time a certain function is called? What I have in mind is something like this:
void foo()
{
print_stack_trace();
// foo's body
return
}
其中, print_stack_trace
的工作方式类似于 主叫
Perl编写的。
Where print_stack_trace
works similarly to caller
in Perl.
或者是这样的:
int main (void)
{
// will print out debug info every time foo() is called
register_stack_trace_function(foo);
// etc...
}
其中, register_stack_trace_function
把一些内部的断点,将导致打印堆栈跟踪每当富
被称为
where register_stack_trace_function
puts some sort of internal breakpoint that will cause a stack trace to be printed whenever foo
is called.
有没有这样的事情在一些标准C库的存在?
Does anything like this exist in some standard C library?
我的工作在Linux上,使用GCC。
I am working on Linux, using GCC.
我有一个表现的不同基础上的一些命令行开关,不应该影响此行为的试运行。我的code的一个伪随机数发生器,我假定基于这些开关被调用不同。我希望能够与每个组开关运行测试,看看是否随机数发生器被不同地称为对每一个。
I have a test run that behaves differently based on some commandline switches that shouldn't affect this behavior. My code has a pseudo-random number generator that I assume is being called differently based on these switches. I want to be able to run the test with each set of switches and see if the random number generator is called differently for each one.
推荐答案
有关可以使用的backtrace(3)仅仅返回数组无效*
(其实每个点的返回地址从相应的堆栈帧)。要翻译这些到使用的东西,有 backtrace_symbols(3)。
For a linux-only solution you can use backtrace(3) that simply returns an array of void *
(in fact each of these point to the return address from the corresponding stack frame). To translate these to something of use, there's backtrace_symbols(3).
,请注意注意到回溯部(3) :
该符号的名称可能是不可用
无需使用特殊的连接器的
选项。
对于使用GNU链接系统,有必要使用
-rdynamic链接
选项。注意,静态函数的名称不被暴露,
并不会
在回溯可用。
The symbol names may be unavailable without the use of special linker options. For systems using the GNU linker, it is necessary to use the -rdynamic linker option. Note that names of "static" functions are not exposed, and won't be available in the backtrace.
这篇关于在C或C打印调用栈++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!