Dan*_*ker 8 c++ debugging methods gcc c++11
有没有办法在C++ 11(使用最新的GCC)中获取调用当前执行的方法(调用者)的方法的名称,或文件和行号?
我想在错误消息中使用此信息,例如,以下代码失败:
void SomewhereInMyProgram()
{
    DoSomething(nullptr);
}
void DoSomething(const char* str)
{
    Contract::Requires(str != nullptr);
    // ...
}
目前我有代码报告错误发生在DoSomething.虽然这在技术上是正确的,但我希望它报告错误发生在SomewhereInMyProgram任何可能的地方.这会让我的生活变得更轻松!
该解决方案可以使用任何C++ 11功能,宏或GCC特定的东西,但不是我必须在每个呼叫站点添加的东西.
我认为堆栈跟踪不会帮助我,因为我不能使用异常处理.实际上,我非常有限:它是一个独立的环境,标准的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的每一次调用,这是唯一的方法.
| 归档时间: | 
 | 
| 查看次数: | 5337 次 | 
| 最近记录: |