有没有办法在运行时访问调试符号?
这是一些示例代码,可以让您了解我想要的内容。
int regular_function(void)
{
int x,y,z;
/** do some stuff **/
my_api_call();
return x;
}
...
void my_api_call(void)
{
char* caller = get_caller_file();
int line = get_caller_line();
printf("I was called from %s:%d\n", caller, line);
}
有没有办法实现 get_caller_file() 和 get_caller_line() ?我见过/使用过像 #define
将 my_api_call
作为函数调用传递 __FILE__
和 __LINE__
的技巧宏。我想知道是否有一种方法可以在运行时而不是编译时访问该信息(假设它存在)?像 Valgrind 这样的东西难道不需要做这样的事情才能获取它返回的信息吗?
Here's some example code to give an idea of what I want.
int regular_function(void)
{
int x,y,z;
/** do some stuff **/
my_api_call();
return x;
}
...
void my_api_call(void)
{
char* caller = get_caller_file();
int line = get_caller_line();
printf("I was called from %s:%d\n", caller, line);
}
Is there a way to implement the get_caller_file()
and get_caller_line()
? I've seen/used tricks like #define
ing my_api_call
as a function call passing in the __FILE__
and __LINE__
macros. I was wondering if there was a way to access that information (assuming it's present) at run time instead of compile time? Wouldn't something like Valgrind have to do something like this in order to get the information it returns?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用调试符号编译了二进制文件,则可以使用特殊库访问它,例如 libdwarf 用于 DWARF 调试格式。
If you have compiled your binary with debug symbols, you may access it using special libraries, like libdwarf for DWARF debug format.
这是高度特定于环境的。在大多数提供调试符号的 Windows 和 Linux 实现中,工具供应商提供或记录了一种执行此操作的方法。为了获得更好的答案,请提供实施细节。
This is highly environment-specific. In most Windows and Linux implementations where debug symbols are provided, the tool vendor provides or documents a way of doing that. For a better answer, provide implementation specifics.
调试符号(如果可用)需要存储在某处,以便调试器可以获取它们。它们可能会也可能不会存储在可执行文件本身中。
您可能知道也可能不知道可执行文件名(
argv[0]
不需要包含程序名称的完整路径,或者确实包含任何有用信息- 请参阅此处了解详细信息)。即使您可以找到调试符号,您也必须对其进行解码才能尝试找出您是从哪里调用的。
并且您的代码可能会被优化到信息无用的程度。
这是很长的答案。简短的答案是,您可能应该像以前一样依赖传入
__FILE__
和__LINE__
。它更加便携和可靠。Debugging symbols, if available, need to be stored somewhere so the debugger can get at them. They may or may not be stored in the executable file itself.
You may or may not know the executable file name (
argv[0]
is not required to have the full path of the program name, or indeed have any useful information in it - see here for details).Even if you could locate the debugging symbols, you would have to decode them to try and figure out where you were called from.
And your code may be optimised to the point where the information is useless.
That's the long answer. The short answer is that you should probably rely on passing in
__FILE__
and__LINE__
as you have been. It's far more portable an reliable.