我的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__