![](/img/trans.png)
[英]How do I get the caller's file name and line number without passing them as parameters?
[英]How to get the name, or file and line of caller method?
C ++ 11中是否有一种方法(使用最新的GCC)来获取调用当前执行的方法 (调用方)的名称或文件和行号?
我想在例如以下代码失败的错误消息中使用此信息:
void SomewhereInMyProgram()
{
DoSomething(nullptr);
}
void DoSomething(const char* str)
{
Contract::Requires(str != nullptr);
// ...
}
目前,我有代码报告在DoSomething
发生的错误。 尽管从技术上讲这是正确的,但我希望它报告该错误可能发生在SomewhereInMyProgram
中。 那会让我的生活变得更加轻松!
该解决方案可以使用任何C ++ 11功能,宏或GCC特定的东西,但不必在每个调用站点中添加。
我认为stacktrace 不能帮助我,因为我不能使用异常处理。 实际上,我非常有限:这是一个独立的环境,其中没有标准的C ++头文件。 我希望有某种宏解决方案。
class Contract
{
public:
static void RequiresImpl(bool condition, const char* expression,
const char* file, int line);
#define Requires(condition) RequiresImpl(condition, #condition , \
__FILE__, __LINE__ )
};
将DoSomething包装在宏中:
void DoSomethingImp(char const *, char const *file, char const *line)
{
// do whatever needed, use file and line to report problems
}
#define DoSomething(x) DoSomethingImp(x, __FILE__, __LINE__)
免责声明:
这不是最好的做法,人们大声疾呼以ANSI或UNICODE方式定义的WIN API宏。 但是我相信,这是您不想更改对DoSomething的每次调用的唯一方法。
据我所知,自动获取有关先前呼叫的信息的唯一方法是使用回溯。 这篇文章有大量的相关信息:
在gcc中,您可以使用以下宏之一: __PRETTY_FUNCTION__
__func__
或__FUNCTION__
或__func__
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.