C++: 创建一个(类似的)”装饰器”,用于自文档化/自打印代码的调试信息

huangapple go评论57阅读模式
英文:

C++: Create a (sort of) "decorator" to self document / self print debug info about code

问题

我已为调试目的创建了以下工作流程。

我定义了一个全局宏

#define PRINT_CALL(x) std::cout << "(CALL) " << x << std::endl

以在调用时通知。在我的用例中,它被如下使用:

void foo() {
    PRINT_CALL("foo()");
    // 做一些事情
}

这使得在我的用例中调试变得更容易。有没有一种自动化这个过程的方法?以下是我想到的 绝对非法 的 C++ 语法:

#define_decorator call_me(x) std::cout << "(CALL) " << x << std::endl

@call_me
void foo() {
    // 做一些事情
}
// ==> 产生与上述完全相同的结果。

我希望你能理解我的意思。正如我所说,语法显然是糟糕的;因为我不知道有这样的功能,也没有在网上找到有用的信息,也许有人知道一个技巧。感谢所有的回答!

英文:

I have for debugging purposes created following workflow.

I defined a global macro

#define PRINT_CALL(x) std::cout &lt;&lt; &quot;(CALL) &quot; &lt;&lt; x &lt;&lt; std::endl

to notify whenever something is called. Trivially it is used like so:

void foo() {
    PRINT_CALL(&quot;foo()&quot;);
    // do stuff
}

This makes debugging much easier in my use case. Is there a way to automate this? Here is what I had in mind in totally illegal C++ syntax:

#define_decorator call_me(x) std::cout &lt;&lt; &quot;(CALL) &quot; &lt;&lt; x &lt;&lt; std::endl

@call_me
void foo() {
    // do stuff
}
// ==&gt; resulting in the exact same outcome as above.

I hope you get the idea. As I said, syntax is obviously trash; since I don't know of such a functionality and didn't find any useful information online, maybe someone knows a hack. Appreciate all answers!

答案1

得分: 0

如果你真的想在你的代码中添加调试注释,你可以根据你的编译器和语言标准使用__FUNCTION____func____PRETTY_FUNCTION__等中的任何一个。例如,定义宏如下所示:

#define PRINT_CALL() std::cout << "(CALL) " << __func__ << std::endl

然后像这样使用它:

void foo() {
    PRINT_CALL(); // 无需重新编写名称 'foo'
    // 做一些事情
}

了解更多信息,请参阅这里:
https://stackoverflow.com/questions/4384765/whats-the-difference-between-pretty-function-function-func

不过,我强烈建议不这样做,考虑使用调试器和断点。

英文:

Assuming you really want to litter your code with debug annotations like this, you could use any of __FUNCTION__, __func__, __PRETTY_FUNCTION__ etc., depending on your compiler and the language standard you are using.
I.e. define the macro like this

#define PRINT_CALL() std::cout &lt;&lt; &quot;(CALL) &quot; &lt;&lt; __func__ &lt;&lt; std::endl

and use it like so

void foo() {
    PRINT_CALL(); // No need to rewrite the name &#39;foo&#39;
    // do stuff
}

See here for more:
https://stackoverflow.com/questions/4384765/whats-the-difference-between-pretty-function-function-func

However I would strongly advise against this and consider using a debugger and breakpoints.

huangapple
  • 本文由 发表于 2023年2月26日 21:29:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572325.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定