如何获得函数调用的文件名和行号? [英] How to get the file name and a line number of a function call?
本文介绍了如何获得函数调用的文件名和行号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在不同的源文件中有两个功能:
I have two functions in different source files:
a.cpp
void A()
{
B();
}
b.cpp
void B()
{
std::cout << "B() called from file: " << ??? << " line: " << ??? << std::endl;
}
如何获取呼叫的文件名和线路号?
How can I get the file name and line number of the call?
推荐答案
通常,您可以通过将函数隐藏在宏调用后自动执行此操作,该宏调用会在 __ FILE __
和 __ LINE __
值
In general you can do this automatically by hiding your function behind a macro call which passes allong the __FILE__
and __LINE__
values
void _B(const char* file, int line) { ... }
#define B() _B(__FILE__, __LINE__)
这绝不是万无一失的解决方案。开发人员可以直接调用 _B
或从生成的代码,程序集等中调用 _B
。 。可能没有有意义的文件/行号
This is by no means a foolproof solution though. It's possible for developers to call _B
directly or for _B
to be called from generated code, assembly, etc .... where there may be no meaningful file / line number
OP要求提供带有参数的示例
OP asked for an example with arguments
void _C(int p1, char p2, const char* file, int line) { ... }
#define C(p1, p2) _C(p1, p2, __FILE__, __LINE__)
这篇关于如何获得函数调用的文件名和行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文