日志C 类方法呼叫者(功能名称,行号)
log C++ class method callers (function name, line number)
我的C 代码中有一个类似于以下的代码:
class myClass
{
public:
void method1(int a, int b, std::string str);
};
其他类可以从myClass实例化对象并调用方法1。
void caller()
{
obj1->method1(12, 4, "sample");
}
我想记录myClass的所有呼叫者(功能名称,文件名,行号)。一种可能的解决方案是:
class myClass
{
public:
method1(int a, int b, std::string str, const char *_function = __builtin_FUNCTION(), const char *_file = __builtin_FILE(), int _line = __builtin_LINE());
};
使用__builtin_xxx作为默认参数。该解决方案有多个缺点:
- 这是一个丑陋的解决方案
- __ hindin_xxx仅在GCC版本> 4.8 中可用
- 我们必须将三个默认参数添加到方法1
- IDE显示了自动完成中的默认参数,这些参数并不是用户提供的!
另一个解决方案是使用__LINE__
,__FILE__
和__func__
,它基本上与以前的解决方案非常相似。它们不是在功能范围之外定义的,应像这样使用:
void caller()
{
obj1->method1(12, 4, "sample", __func__, __FILE__, __LINE__);
}
这是两个解决方案的工作示例。
当用户在myClass对象上调用Method1时,是否有任何更好的解决呼叫者的解决方案。通过更好的解决方案,我特别是指通过添加三个参数来更改Method1的声明!
另一个丑陋的解决方案,但我正在使用...
使用宏自动添加__LINE__
__FILE__
...等。事物变成参数。
例如
#define Method(param0,param1) Method(param0,param1,__LINE__)
它有很多问题,如果您要宏作为正常功能工作,则必须做很多事情,并且可能仍然无法正常工作。
我用它来帮助我记录错误。
看起来像打印的副本,呼叫功能的文件名,行号和功能名称-C prog
I'd pass the data to the function through parameters (maybe get the help of a macro)
int info(const char *fname, int lineno, const char *fxname, ...) { /* ... */ }
int debug(const char *fname, int lineno, const char *fxname, ...) { /* ... */ }
int error(const char *fname, int lineno, const char *fxname, ...) { /* ... */ }
And to call them
info(__FILE__, __LINE__, __func__, ...);
debug(__FILE__, __LINE__, __func__, ...);
error(__FILE__, __LINE__, __func__, ...);
Note: __func__ is C99; gcc, in mode C89 has __FUNCTION__
相关文章:
- 预处理器:插入结构名称中的前一个行号
- 如何在文件和行号中抛出错误
- Qt 调试显示行号
- 不带预处理器的调用方法/文件的文件名/行号
- 提升堆栈跟踪不显示函数名称和行号
- 如何打印源文件中与 GDB 中的程序流关联的所有行号
- 如何构建一个异常类来报告C++中的哪些文件和行号?
- MinGW 上的 g++ 在使用 SDL2 时无法保留行号信息
- _CrtSetAllocHook - 空文件名和行号参数
- addr2line get 行号始终返回 0
- 获取调用函数调用的C++程序中的所有行号
- CRT 不打印内存泄漏的行号
- C++ 删除文本文件中的特定行号
- 如何使用谷歌测试隐藏行号
- 如何从CPP源代码行号中获取LLVM位码行号?
- 如何在QT中的QtableView中找到我的按钮的行号
- 如何打印通话函数的行号和文件名而不是log.cpp
- 谷歌测试有没有办法为被调用函数中的断言生成调用方行号
- 如何在qtablewidget中获取字符串的行号
- 日志C 类方法呼叫者(功能名称,行号)