【问题标题】:log C++ class method callers (function name, line number)记录 C++ 类方法调用者(函数名、行号)
【发布时间】:2017-10-01 04:40:27
【问题描述】:

我的 C++ 代码中有一个类,类似于以下内容:

class myClass
{
public:
  void method1(int a, int b, std::string str);
};

其他类可以从myClass 实例化一个对象并调用method1。

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 作为默认参数。该解决方案有多个缺点:

  1. 这是一个丑陋的解决方案
  2. __builtin_xxx 仅适用于 gcc 版本 > 4.8
  3. 我们要给method1添加三个默认参数
  4. IDE 在自动完成时显示默认参数,这些参数并非由用户提供!

另一个解决方案是使用__LINE____FILE____func__,这与之前的解决方案基本非常相似。它们没有在函数范围之外定义,它们应该像这样使用:

void caller()
{
    obj1->method1(12, 4, "sample", __func__, __FILE__, __LINE__);
}

Here 是这两种解决方案的工作示例。

当用户在 myClass 对象上调用 method1 时,是否有任何更好的 解决方案来记录调用者。通过更好的解决方案,我的意思是不要通过添加另外三个参数来更改方法 1 的声明!

【问题讨论】:

标签: c++


【解决方案1】:

另一个丑陋的解决方案,但我正在使用......

使用宏自动添加__LINE__ __FILE__ ...等。东西变成参数。

例如

#define Method(param0,param1) Method(param0,param1,__LINE__)

有很多问题,如果你想让宏像正常功能一样工作,你必须做很多事情,它仍然可能不起作用。

我用它来帮助我记录错误。

【讨论】:

  • 我不认为这个答案是更好的解决方案!我已更新我的问题以澄清更多信息。
【解决方案2】:

看起来像 Print the file name, line number and function name of a calling function - 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__

【讨论】:

  • 我不认为这个答案是更好的解决方案!我已更新我的问题以澄清更多信息。
猜你喜欢
  • 1970-01-01
  • 2023-03-20
  • 2014-08-06
  • 2011-05-29
  • 2018-11-02
  • 1970-01-01
  • 1970-01-01
  • 2015-09-16
  • 2015-12-19
相关资源
最近更新 更多